Skip to content

Instantly share code, notes, and snippets.

@jdfm
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdfm/7ba6a1de56a8c0938f89 to your computer and use it in GitHub Desktop.
Save jdfm/7ba6a1de56a8c0938f89 to your computer and use it in GitHub Desktop.
Reducing "if" nesting - via http://qr.ae/f3BuB
// 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;
@jdfm
Copy link
Author

jdfm commented Jun 23, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment