Skip to main content

Cleaner If Statements

  • I’m a big fan of the pattern shown in the video by Basarat Ali of guard clauses with early returns rather than nesting conditional statements

Nested conditional statements are hard to read and understand at a glance. They require the reader to keep track of the state of the program in their head, which is cognitively expensive. The more cognitive load a reader has to carry, the more likely they are to make a mistake.

Guard clauses with early returns are easier to read and understand at a glance. They allow the reader to focus on one condition at a time, and they allow the reader to see the happy path of the program without having to keep track of the state of the program in their head.

Example of nested conditional statements:

if (user) {
  if (user.isVerified) {
    if (user.isPremium) {
      // do something
    } else {
      // do something else
    }
  } else {
    // do something else
  }
} else {
  // do something else
}

Same example using guard clauses with early returns:

if (!user) {
  return
}
 
if (!user.isVerified) {
  return
}
 
if (!user.isPremium) {
  return
}
 
// do something

Further reading

Inbox

  • the very first idea in Tidy First? is to replace typical if statements with prerequisite guard clauses
  • see article about moving the happy path all the way left (i.e. don’t indent code that’s on the happy path; indent the exceptions)