DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Lane Wagner for Boot.dev

Posted on • Originally published at qvault.io on

Guard Clauses: How to clean up Conditionals

One of the first techniques developers learn is the if/else statement. For obvious reasons if/else statements are a primary way to create logic trees, where calculations are handled differently depending on the input variables. However, complex and nested if/else statements become a cognitive burden to reason about, and can be hard for the next developer to understand quickly.

Guard Clauses

Guard Clauses are a way to leverage the ability to return early from a function (or break/continue through a loop) to make nested conditionals more one-dimensional.

I’m primarily a go developer, and the way errors are handled in go naturally encourage the developer to make use of guard clauses. When I started writing more javascript, I was disappointed to see many how many nested conditionals existed in the code I was working on.

Go is the shit

Let’s take a look at a fake javascripty example:

function getInsuranceAmount(status) {
  let amount;
  if (!status.hasInsurance()){
    amount = 1;
  } else {
    if (status.isTotaled()){
      amount = 10000;
    } else {
      if (status.isDented()){
        amount = 160;
        if (status.isBigDent()){
          amount = 270;
        }
      }
    }
  }
  return amount;
}
Enter fullscreen mode Exit fullscreen mode

Could be written with guard clauses instead:

function getInsuranceAmount(status) {
  if (!status.hasInsurance()){
    return 1;
  }
  if (status.isTotaled()){
    return 10000;
  }
  if (status.isDented() && status.isBigDent()){
    return 270;
  }
  if (status.isDented()){
    return 160;
  }
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

The example above still probably isn’t the best way to approach this function, but it is much easier to read and understand. When writing code, it is important to try to reduce cognitive load on the reader by reducing the amount of things they need to think about at any given time.

In the first example, if the developer is tying to figure out when 270 is returned, they need to think about each branch in the logic tree and try to remember which cases matter and which cases don’t. With a more one dimensional structure, its as simple as stepping through each case in order.

I hope this helps us to create more readable code! I think it’s great to learn the patterns and best practices that exist in programming languages we aren’t familiar with, because many times those techniques can be applied to programming in general.

By Lane Wagner

Download Qvault: https://qvault.io

Subscribe to our RSS Feed: https://qvault.io/blog/feed/

Star our Github: https://github.com/q-vault/qvault

The post Guard Clauses: How to clean up Conditionals appeared first on Qvault.

Top comments (2)

Collapse
 
couch3ater profile image
Connor Tangney • Edited on

Guards are fantastic! While your Javascript syntax is perhaps the most verbose, guards can also be written as follows:

//a variable to test with
let a = 'a';

//condition && result
a === 'a' && console.log('yes it does!');
Enter fullscreen mode Exit fullscreen mode

You may notice this looks similar to the ternary operator. This is great for one-liners (like return codes πŸ˜‰) but should not be used for complex / multi-line statements:

//a variable to test with
let a = 'a';

//condition && result
// !! THIS WON'T WORK !!
a === 'a' && (
  console.log('did this work?')
  console.log('no :(')
);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ombratteng profile image
Ole-Martin Bratteng • Edited on
//a variable to test with
let a = 'a';

//condition && result
// !! THIS WILL WORK !!
a === 'a' && (
  console.log('did this work?'),
  console.log('yes :)')
);
Enter fullscreen mode Exit fullscreen mode

replit.com/@omBratteng/guard-claus...

🌚 Life is too short to browse without dark mode