越来越多我发现自己编写的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();
}
现在,对我而言,这看起来很恐怖。有没有人有更清晰的方式来表示这种逻辑?
答案 0 :(得分:2)
问题原样有三种情况: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();
}
对于这种简单的情况,我通常更喜欢如上所述展平结构。对于更复杂的情况,最终可能更容易嵌套,甚至更好地将测试减少到某种结构(列表或整数,具体取决于您的语言)并打开该值。