How to write better code with Guard Clauses

in #technology5 months ago

image.png

In the spirit of the 10,000+ Hive Hackathon I am running, I am going to try to put out some tips and tricks over the next few days.

I also have a long-running Python Tips Series you can find here.
Look at the footer for links to the previous entries.

What is a Guard Clause

A guard clause a programming idiom that you are likely already using but are not aware there is a name for it. It is also something you are not likely using effectively.

A guard clause exits a loop or function when certain conditions are met early on.

Example 1

let inventory = 1
let cart = []

function addToCart(item){
  if (inventory > 0) {
    cart.push(item)
  }
}

addToCart('Book')
console.log(cart)

This simple code creates a variable to simulate an inventory and a shopping cart. There is an addToCart() function to add items to the cart. Before adding an item to the cart, it checks to see if the inventory is empty.

This code works perfectly fine and is easy to read. The problem comes in when the business rules become more complex and you start expanding the if statement.

Example 2

let inventory = 1
let cart = []
let userIsLoggedIn = true

function addToCart(item){
  if (userIsLoggedIn) {
    if (inventory > 0) {
      cart.push(item)
    }
  }

}

addToCart('Book')
console.log(cart)

While this is still relatively simple, you have likely coded far more complex examples many times. These types of nested if structures become very difficult to manage and change in the future.

Introducing the guard clause

A guard clause will exit your loop or function immediately. This avoids additional indents to your core condition statements making them far easier to read and maintain.

let inventory = 1
let cart = []
let userIsLoggedIn = true

function addToCart(item){
  if (!userIsLoggedIn || !inventory) return
  cart.push(item)
}

addToCart('Book')
console.log(cart)

By extracting the initial sanity checks into a dedicated if statement that exits immediately, your code is cleaner and far easier to maintain.

These examples are oversimplified, and real-life examples are far more difficult to work with.

Here's an example of an if cluster bomb from Reddit

const returnLinesRequiredData = (lineObj, id, key) => {

  if (id) {
    if (id < lineObj.stations.length) {
      if (key) {
        if (lineObj.stations[id].hasOwnProperty(key)) {
          return lineObj.stations[id][key];
        }
        return errorMsg;
      }
      return lineObj.stations[id];
    }
    return errorMsg;
  }
  return lineObj;

};

Source

Try to look over your existing code and see where you can implement guard clauses to improve the readability of your code.


Securely chat with me on Keybase

Why you should vote me as witness

Sort:  
Loading...

Will try to make some great codes...

I keep thinking that I need to learn to code. Or at least get the basics down. Seeing how I don't see a future where I'm not involved in crypto in some shape or form. Just logged into hive for the first time. Still have some learning on how things work now. But I wasn't at all surprised to see you still working hard. God Bless. :)

I keep thinking that I need to learn to code.

Same.

That's a great advice, we usually exit early and do all the error check before doing any heavy operations.

I know a lot of programmers prefer the guard clause with a lot of returns, but I prefer structured ifs as in Example 1 and 2 but write a short comment after the closing if bracket, if the if statement gets very long.

Funny, I never knew this was called a guard clause. I seem to use them more often now than ever in this new era of love for weakly-typed languages.

stuff like

function whatever(value){
    if (isNaN(value))
        return false;
    ...
    ...
    return true;
}

I wish Javascript were more like this (at least optionally):

private function whatever(value:Number):Boolean{
    // Throws an error if passed value is not of type Number
    ...
    return true;
}

With languages like JS I spend most of my time trying to debug where the hell the issue is even coming from. I suppose some people like the flexibility of not declaring types, though. I know you can use something like TypeScript but it would be nice if one could optionally static type and run it natively in the browser.

But I digress... Nice to know what it's called a guard clause!

I have heard it termed as the happy path. Where as you work your way down the function you return out the "un-happy" steps.

Keep up the great tutorials @TheMarkyMark !!