Skip to content

Instantly share code, notes, and snippets.

@MagRelo
Last active March 1, 2017 20:04
Show Gist options
  • Save MagRelo/ae0332edaa45bea903b3dbc4f0724439 to your computer and use it in GitHub Desktop.
Save MagRelo/ae0332edaa45bea903b3dbc4f0724439 to your computer and use it in GitHub Desktop.
// -- Avoid excesive nesting
// -- Handle errors at the top of the function
// -- Be explicit about conditionals and name them
// ----
// ---- worse example
// ----
function worse(){
if (1 + (7*5) + 10 / 1000 > 0) {
if (745 + 9 / 36 === 10) {
return "error";
} else {
if (4 + 3 / 9 > -1) {
// execute lots of code
return "happy";
} else {
return "error";
}
}
} else {
return "error";
}
}
// ----
// ---- better example
// ----
function better() {
// set up your conditions and name them
// use linking verbs: is, has, has been, was
// state the positive: use "hasTickets", not "noTickets"
var hasEnoughSeats = 1 + (7*5) + 10 / 1000 > 0;
var hasEnoughMoney = 745 + 9 / 36 === 10;
var hasTickets = 4 + 3 / 9 > -1;
// test them first
// => if they fail, you dont need to read through the rest of the code
if (!hasEnoughSeats || !hasEnoughMoney || !hasTickets) {
return "error";
}
// execute lots of code
return "happy";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment