What is the difference between nested and cascaded if-else?
These two are equivalent:
if (condition1) block1
else if (condition2) block2
if (condition1) block1
else
{
if (condition2) block2
}
I presume they also compile to the same assembly, so there should be no difference.
I depends on how you arrange them. A nested if is equivalent to adding an and to each of the inner ifs:
if(A) {
if(B) {
statement1
}
else if(C) {
statement2
}
}
is equivalent to:
if(A and B) {
statement1
}
else if(A and C) {
statement2
}
My advice is to strive for readability and check your logic. You may find DeMorgan's Laws useful for re-arranging your logic.
Here's one that always irritates me:
if(A and B) {
statement1
statement2
}
else if(A and C) {
statement1
statement3
}
else if(not A) {
statement4
}
vs
if(A) {
statement1
if(B) {
statement2
}
else if(C) {
statement3
}
}
else if(not A) {
statement4
}
I'm just not sure which is more readable. They are logically equivalent. The first is more tabular and easier on the eye but repeats statement1; the second is more nested and a little uglier (to my eye) but does not repeat statements. Ultimately it's a judgment call because it makes no difference to the compiler.
Nested if-then-else
control structures are minimized translations of complex logic rules. They are good in avoiding redundancy in checking conditions. Their main drawback is that in the long run these structures can grow and make enclosing methods too big and complex. First step in breaking nested if-then-else
blocks is normalization. For example:
if (A) {
if (B || C) {
block 1;
} else {
if (!D) {
block 2;
}
}
} else {
block 3;
}
can be normalized to cascaded if-then-else
if (A && (B || C) {
block 1;
return;
}
if (A && !B && !C && !D) {
block 2;
return;
}
if (!A) {
block 3;
}
We have eliminated else
blocks and made further extract method refactoring easy. All three if blocks can be extracted to separate methods named after the business logic their bodies execute.