适当使用嵌套 If 语句

Appropriate Use of Nested If Statement

显然,嵌套 if 语句是允许的。所以看起来它们可能有适当的用途。每个人都讨厌它们,我想知道是否有时嵌套 if 语句是最好的做法。这是我认为最好使用嵌套语句的示例:

if (A){
    //Code for A
    if (B){
        //Code for B
    } else {
        //Code for !B
    }
    //More A Code
} else {
    //Code for !A
    if (C){
        //Code for C
    } else {
        //Code for !C
        if (D){
            //code for D
        }
    }
}

如果我尝试不嵌套这段代码,结果会是这样:

if (A&&B){
    //Code for A
    //Code for B
    //More A Code
}
if (A&&!B){
    //Code for A
    //Code for !B
    //More A Code
}
if (!A&&C){
    //Code for !A
    //Code for C
}
if (!A&&!C&&D){
    //Code for !A
    //Code for !C
    //Code for D
}
if (!A&&!C&&!D){
    //Code for !A
    //Code for !C
}

一开始这看起来更干净,直到你真的把代码放在那里并且有冗余,这是一场噩梦。

if (A){
    //Code for A
}
if (A&&B){
    //Code for B
}
if (A&&!B){
    //Code for !B
}
if (A){
    //More A Code
}
if(!A){
    //Code for !A
}
if(!A&&C){
    //Code for C
}
if(!A&&!C){
    //Code for !C
}
if(!A&&!C&&D){
    //Code for D
}

这种方式不使用嵌套语句,也不需要重写代码,但它过度使用了条件并且比原来有更多的 if() 实例。此外,你必须做更多的阅读而不是略读才能看到 B 仅在 A 为真时才被评估。然后如果你在底部放一个 if(A&&C) 之类的东西就变得更难维护了。

嵌套 if 语句对我来说似乎是最合理的,因为它们具有最少的 if() 实例。我不明白为什么每个人都讨厌嵌套的 if 语句。有没有人有更实用的方法来编写这段代码?还是我误解了人们对嵌套 if 的意思?好像每道关于嵌套if的题都没有第一层的代码,比如:

if(A){
    if(B){
        //Do Something
    } else {
        //Do Something Else
    }
} else {
    //Do Third thing
}

等等...不,那个人仍然会使用 if() 的更多实例来尝试缩短它。我想到的 有两个相同的语句。任何人,这些示例是适当的嵌套 if 语句,还是有 better/clearer/cleaner/faster/more-standard 编写此代码的方法?

嵌套的 if 语句在不必要的情况下是讨厌的。通常有办法将它们变成 less complex code, sometimes not obvious but nonetheless possible. If your problem is however essentially complex,然后嵌套 if 语句完全可以对其进行编码。