create account

How to write better code with Guard Clauses by themarkymark

View this thread on: hive.blogpeakd.comecency.com
· @themarkymark ·
$39.99
How to write better code with Guard Clauses
![image.png](https://files.peakd.com/file/peakd-hive/themarkymark/pRGrxeW8-image.png)

In the spirit of the [10,000+ Hive Hackathon](https://peakd.com/stem/@themarkymark/stemgeek-s-first-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](https://peakd.com/hive-163521/@themarkymark/python-tips-easy-serialization-with-pickle).  
*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;

};
```
<sub>[Source](https://stackoverflow.com/questions/42347068/callback-hell-in-multiple-if-else-if-statements)</sub>

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


---

<center>Securely chat with me on [Keybase](https://keybase.io/officialmarky)
<center>https://steemitimages.com/DQmcWxV1dpA1eAtw2ipwZiWZkydyVNU5LaLa2Ak1GUnbGmS/The-Marky-Mark.png </center>
# <center>  [Why you should vote me as witness](https://peakd.com/witness-category/@themarkymark/why-you-should-vote-for-themarkymark-as-witness)  </center> #
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 319 others
👎  ,
properties (23)
authorthemarkymark
permlinkhow-to-write-better-code-with-guard-clauses
categorytechnology
json_metadata{"app":"peakd/2020.04.5","format":"markdown","tags":["technology","programming","tutorial","palnet","neoxian","dev"],"users":["themarkymark"],"links":["/stem/@themarkymark/stemgeek-s-first-hackathon","/hive-163521/@themarkymark/python-tips-easy-serialization-with-pickle","https://stackoverflow.com/questions/42347068/callback-hell-in-multiple-if-else-if-statements","https://keybase.io/officialmarky","/witness-category/@themarkymark/why-you-should-vote-for-themarkymark-as-witness"],"image":["https://files.peakd.com/file/peakd-hive/themarkymark/pRGrxeW8-image.png","https://steemitimages.com/DQmcWxV1dpA1eAtw2ipwZiWZkydyVNU5LaLa2Ak1GUnbGmS/The-Marky-Mark.png"]}
created2020-05-03 00:02:36
last_update2020-05-03 00:02:36
depth0
children9
last_payout2020-05-10 00:02:36
cashout_time1969-12-31 23:59:59
total_payout_value22.232 HBD
curator_payout_value17.758 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length3,412
author_reputation1,774,988,226,591,842
root_title"How to write better code with Guard Clauses"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id97,149,597
net_rshares60,648,510,252,624
author_curate_reward""
vote details (385)
@codingdefined ·
That's a great advice, we usually exit early and do all the error check before doing any heavy operations.
properties (22)
authorcodingdefined
permlinkre-themarkymark-202053t123320768z
categorytechnology
json_metadata{"tags":["technology","programming","tutorial","palnet","neoxian","dev"],"app":"esteem/2.2.5-mobile","format":"markdown+html","community":"hive-125125"}
created2020-05-03 07:03:21
last_update2020-05-03 07:03:21
depth1
children0
last_payout2020-05-10 07:03:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length106
author_reputation529,462,591,834,917
root_title"How to write better code with Guard Clauses"
beneficiaries
0.
accountesteemapp
weight300
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id97,154,272
net_rshares0
@cryptosharon · (edited)
I usually just make some big if conditions haha.

I also use something I love, I'll show it here.

Let's say you want to extract "avatar" from this object:

```
{
  id: 123456,
  data: {
    type: "message",
    user: {
      "name": "user123",
      "user_id": 1235612,
      "avatar": "https://example.com/avatars/user123_afk20s_3a.jpg"
    },
    body: "test"
  }
}
```

It could be problematic if there is no response.data.user because it's a system message, for example, or it's not a message, or if the user has no avatar, etc. Whenever the API's are poorly made and somewhat inconsistent on the keys, there is a very easy solution.

Instead of doing this:

```
let pfp;
if (response && response.data && response.data.user && response.data.user.avatar) {
  pfp = response.data.user.profile_picture;
}
```

We can do it all more easily like this:

```
const pfp = ((((response||{}).data||{}).user||{}).profile_picture||"https://example.com/avatars/default.jpg)
```

At any failure, instead of throwing an error, it goes to undefined and picks the empty object, and if the last property is still undefined, it grabs the default.

edit: (this is obviously not made for features that require you to display a specific error of what is lacking from the input)
👍  
properties (23)
authorcryptosharon
permlinkre-themarkymark-q9qh90
categorytechnology
json_metadata{"tags":["technology"],"app":"peakd/2020.04.5"}
created2020-05-03 02:22:12
last_update2020-05-03 02:33:27
depth1
children0
last_payout2020-05-10 02:22:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,260
author_reputation91,921,317,551,639
root_title"How to write better code with Guard Clauses"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id97,151,059
net_rshares11,639,480,790
author_curate_reward""
vote details (1)
@dreamingirwin ·
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. :)
properties (22)
authordreamingirwin
permlinkq9qmv8
categorytechnology
json_metadata{"app":"hiveblog/0.1"}
created2020-05-03 04:23:33
last_update2020-05-03 04:23:33
depth1
children1
last_payout2020-05-10 04:23:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length338
author_reputation19,858,177,829,580
root_title"How to write better code with Guard Clauses"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id97,152,489
net_rshares0
@r0nd0n ·
> I keep thinking that I need to learn to code.

Same.
properties (22)
authorr0nd0n
permlinkre-dreamingirwin-q9rijw
categorytechnology
json_metadata{"tags":["technology"],"app":"peakd/2020.05.1"}
created2020-05-03 15:48:00
last_update2020-05-03 15:48:00
depth2
children0
last_payout2020-05-10 15:48:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length54
author_reputation30,016,317,522,307
root_title"How to write better code with Guard Clauses"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id97,161,759
net_rshares0
@hackrelentless ·
Keep up the great tutorials @TheMarkyMark !!
properties (22)
authorhackrelentless
permlinkre-themarkymark-q9vn3m
categorytechnology
json_metadata{"tags":["technology"],"app":"peakd/2020.04.5"}
created2020-05-05 21:16:36
last_update2020-05-05 21:16:36
depth1
children0
last_payout2020-05-12 21:16:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length44
author_reputation6,101,322,881
root_title"How to write better code with Guard Clauses"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id97,207,876
net_rshares0
@nuthman ·
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](https://esdiscuss.org/topic/es8-proposal-optional-static-typing) and run it natively in the browser. 

But I digress... Nice to know what it's called a guard clause!
👍  
properties (23)
authornuthman
permlinkre-themarkymark-q9s2aa
categorytechnology
json_metadata{"tags":["technology"],"app":"peakd/2020.04.5"}
created2020-05-03 22:54:12
last_update2020-05-03 22:54:12
depth1
children1
last_payout2020-05-10 22:54:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length915
author_reputation344,453,626,754,867
root_title"How to write better code with Guard Clauses"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id97,168,527
net_rshares0
author_curate_reward""
vote details (1)
@souris ·
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. 
properties (22)
authorsouris
permlinkre-nuthman-qdmfyl
categorytechnology
json_metadata{"tags":["technology"],"app":"peakd/2020.07.1"}
created2020-07-17 16:18:24
last_update2020-07-17 16:18:24
depth2
children0
last_payout2020-07-24 16:18:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length124
author_reputation22,834,205,494
root_title"How to write better code with Guard Clauses"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,572,797
net_rshares0
@steem0 ·
Will try to make some great codes...
properties (22)
authorsteem0
permlinkre-themarkymark-202053t71542132z
categorytechnology
json_metadata{"tags":["technology","programming","tutorial","palnet","neoxian","dev"],"app":"esteem/2.2.5-mobile","format":"markdown+html","community":"hive-125125"}
created2020-05-03 01:45:42
last_update2020-05-03 01:45:42
depth1
children0
last_payout2020-05-10 01:45:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length36
author_reputation907,702,232,817
root_title"How to write better code with Guard Clauses"
beneficiaries
0.
accountesteemapp
weight300
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id97,150,692
net_rshares0
@vikisecrets ·
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.
properties (22)
authorvikisecrets
permlinkre-themarkymark-q9r0v9
categorytechnology
json_metadata{"tags":["technology"],"app":"peakd/2020.04.5"}
created2020-05-03 09:25:54
last_update2020-05-03 09:25:54
depth1
children0
last_payout2020-05-10 09:25:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length216
author_reputation1,199,516,530,996,327
root_title"How to write better code with Guard Clauses"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id97,156,079
net_rshares0