Nested if statements are allowable, obviously. So it seems that there might be an appropriate use for them. Everyone hates on them, and I was wondering if there are times when nested if statements are the best course of action. Here's an example of what I think might be best to use a nested statement for:
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 I were to try to not nest this code, it would turn out as follows:
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
}
This looks cleaner at first, until you actually put code in there and have redundancies, which are a nightmare.
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
}
This way doesn't use nested statements, and doesn't require rewriting code, but it overuses conditions and has more if() instances than the original. Also, you have to do more reading than skimming to see that B is only evaluated if A is true. And then it becomes harder to maintain if you put an if(A&&C)
at the bottom or something.
The Nested if statements seem to be the most reasonable to me because they have the fewest instances of if()
. I don't understand why everyone hates on nested if statements. Does anyone have a more practical way to write this code? Or do I misunderstand what people mean regarding nested ifs? It seems that every question regarding nested ifs have no code in the first layer, such as:
if(A){
if(B){
//Do Something
} else {
//Do Something Else
}
} else {
//Do Third thing
}
Wait... no, that one still would use more instances of if()
to try to shorten it. The particular example I was thinking of had two of the same statement. Anywho, are these examples of appropriate nested if statements, or is there a better/clearer/cleaner/faster/more-standard way of writing this code?