Last active
August 29, 2015 14:21
-
-
Save jdfm/7ba6a1de56a8c0938f89 to your computer and use it in GitHub Desktop.
Reducing "if" nesting - via http://qr.ae/f3BuB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Original nested version | |
if ( a > 0 ) { | |
if ( b > 10 ) { | |
if ( c > 0 ) { | |
//complex code | |
} | |
} | |
} | |
return; | |
// ----------------------------------- | |
// this version is better if you have various | |
// conditions that take a while to calculate | |
if ( a > 0 ) { | |
return; | |
} | |
if ( b > 10 ) { | |
return; | |
} | |
if ( c > 0 ) { | |
//complex code | |
} | |
return; | |
// ----------------------------------- | |
// More descriptive alternative | |
var OK = false; | |
OK = OK && ( a > 0 ); // Comment why | |
OK = OK && ( b > 10 ); // Comment why | |
OK = OK && ( c > 0 ); // Comment why | |
if ( OK ) { // Good to go | |
// Do your stuff | |
} | |
return; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The last variant is useful in loops where you have to check all items and report on the general status of the entire collection, think form validation.