【发布时间】:2014-09-08 04:30:13
【问题描述】:
最近,我经常写出这样的代码:
def doSomethingWithLotsOfConditions(arg1, arg2, arg3...) {
arg1.get(arg2) match {
case Some(value1) =>
arg3.get(value1) match {
case Some(value2) =>
arg4.get(arg5, value2) match {
case Some(value3) =>
finallyDoSomethingInside(value3)
case None =>
log("Some excuse for being unable to work with arg4/arg5...")
}
case None =>
log("Some excuse for being unable to work with arg3")
}
case None =>
log("Some excuse for being unable to work with arg1/arg2")
}
}
somewhat related question 似乎大力提倡使用嵌套的match,尽管从我的角度来看,它似乎难以阅读、简洁或易于理解:(1) 它有点拆分支票本身及其后果,(2)它使代码无法控制地嵌套,没有任何真正的嵌套理由。在这些特殊情况下,我很乐意将代码构造成以下几行:
def doSomethingWithLotsOfConditions(arg1, arg2, arg3...) {
// Step 1
val value1Opt = arg1.get(arg2)
if (value1Opt.isEmpty) {
log("Some excuse for being unable to work with arg1/arg2")
return
}
val value1 = value1Opt.get
// Step 2
val value2Opt = arg3.get(value1)
if (value2Opt.isEmpty) {
log("Some excuse for being unable to work with arg3")
return
}
val value2 = value2Opt.get
// Step 3
val value3Opt = arg4.get(arg5, value2)
if (value3Opt.isEmpty) {
log("Some excuse for being unable to work with arg4/arg5...")
return
}
val value3 = value3Opt.get
// All checked - we're free to act!
finallyDoSomethingInside(value3)
}
然而,这种模式(即valueXOpt = (...).get => 检查isEmpty => value = valueXOpt.get)看起来真的很难看,而且也绝对过于冗长。见鬼,Java 版本看起来更简洁:
Value1Type value1 = arg1.get(arg2);
if (value1 != null) {
log("Some excuse for being unable to work with arg1/arg2");
return;
}
是否有更好、更简洁的替代方案,即获取值并指定替代的短逃逸路线(log 一行 + return),而不需要与匹配项嵌套?
【问题讨论】:
标签: scala nested pattern-matching