1

越来越多的我发现自己在编写一个看起来像这样的 If 语句结构:

if(something) {
  if(somethingElse) {
     // If both evaluate to true.
     doSomething();
  }
  else {
     // If the first if is true but the second is not.
     doSomethingElse();
  }
}
else {
     // If the first evaluates the false.
     doSomethingDifferent();
}

现在,对我来说,这看起来很可怕。有没有人有更简洁的方式来表示这个逻辑?

4

1 回答 1

2

问题原样具有三种情况:something & somethingelsesomething & !somethingelse!something。另一种方法是将其分解为具有三个分支的 if-else:

if(something & somethingElse) {
     // If both evaluate to true.
     doSomething();
  }
elif(something) { // explicit test of somethingElse falsity not required
     // If the first if is true but the second is not.
     doSomethingElse();
  }
else {
     // If the first evaluates the false.
     doSomethingDifferent();
}

对于这样一个简单的情况,我通常更喜欢将上面的结构展平。对于更复杂的情况,它最终可以更简单地嵌套,或者甚至更好地将您的测试简化为某种结构(取决于您的语言的列表或整数)并打开该值。

于 2013-09-04T20:10:16.220 回答