Monday, September 5, 2016

(#1) Programming tips learned by years of coding - Reducing nested "if's"

- Try to reduce NESTED IF's

- Below(Approach 1) is "ArrowHead Anti-Pattern" and Approach 2 and Approach 3 are ways to avoid this antipattern.

- Don't nest if's if you need to check for multiple conditions. The problem with the nested "if" is that there could be a matching "else" further down the page. Doing the early exits means you don't have to keep track of that option, making the code easier to understand.

--------------------------------------------------------------------------------------------------
Approach 1: Original code

if(a > 0) {
                     //one or two lines simple code

                      if( b > 10 ) {
                                                //one or two lines simple code

                                                 if(c > 0) {
                                                                    //complex code
                                                 }
                      }
 }

Drawback: complex code, See the arrowhead above ?
---------------------------------------------------------------------------------------------------------
Approach 2: Early return

if (a < 1 ) {
                    return
 }
//one or two lines simple code

if (b < 11 ) {
                     return
 }
//one or two lines simple code

if (c < 1 ) {
                    return
 }

//complex code 

 Drawback: Better but multiple returns! Compiler optimisation might get affected. Compiler mostly prefers single entry - single exit to optimise the source code.

---------------------------------------------------------------------------------------------------------

Approach 3: Steve Barnes below has an even better solution that takes care of the early returns.

bool OK = FALSE;
bool OK = FALSE;
OK = (a > 0); // Comment why
//one or two lines simple code

OK &= (b > 10); // Comment why
//one or two lines simple code

OK &= (c > 0); // Comment why
if OK { // Good to go
                 //complex code

return; // just one simple return

---------------------------------------------------------------------------------------------------------
The Steve Barners approach (approach 3) should only be used when there are other codes between "nested if" statements. But again coding is like painting, there could not be hard and fast rules for everything. Just go with your instinct But, Just be careful!

For clarity: If there are no other code between "ifs" simply do it this way.
If ( (a > 0) && ( b > 10 ) && (c > 0) ) {
            //complex code
 }
Reference: Jacques du Rand, Quora