越来越多地,我发现自己写了一个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();
}现在,在我看来,这看起来很可怕。有没有人有一种更清晰的方法来表达这个逻辑?
发布于 2013-09-04 20:10:16
这个问题有三个例子:something & somethingelse、something & !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();
}对于这样一个简单的例子,我通常更喜欢像上面那样把结构压平。对于更复杂的情况,嵌套可能会更简单,或者更好的做法是将测试简化为某种结构(列表或整数,取决于您的语言)并打开该值。
https://stackoverflow.com/questions/18405747
复制相似问题