What is the difference between nested and cascading if-else

What is the difference between nested and cascading if-else?

+4
source share
3 answers

These two equivalents:

if (condition1) block1 else if (condition2) block2 if (condition1) block1 else { if (condition2) block2 } 

I assume that they will also compile into the same assembly, so there should be no difference.

+4
source

Depending on how you organize them. A nested if is equivalent to adding a to each of the internal 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 test your logic. You may find DeMorgan Laws useful for re-organizing your logic.

It always annoys me here:

 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 what is more readable. They are logically equivalent. The first is more tabular and simpler by eye, but repeats statement 1; the second is more nested and a little ugly (in my opinion), but does not repeat the statement. Ultimately, this is a solution because it has nothing to do with the compiler.

+2
source

Nested if-then-else control structures are minimized translations of complex logical rules. They are good at preventing redundancy under test conditions. Their main drawback is that ultimately these structures can grow and make complex methods that are too large and complex. The first step in breaking up nested if-then-else blocks is normalization. For instance:

 if (A) { if (B || C) { block 1; } else { if (!D) { block 2; } } } else { block 3; } 

can be normalized to cascading if-then-else

 if (A && (B || C) { block 1; return; } if (A && !B && !C && !D) { block 2; return; } if (!A) { block 3; } 

We removed the else blocks and simplified the refactoring process. All three if blocks can be extracted to separate methods named after the business logic executed by their bodies.

+1
source

Source: https://habr.com/ru/post/1305387/


All Articles