Use Guard Clauses for Cleaner Code

Mar 24th, 2022

The guard clause is a nifty pattern that provides a super-simple way to clean up your code. Their main function is to terminate a block of code early, which reduces indentation of your code and therefore makes your code much easier to read and reason about.

Too often, I see entire method bodies wrapped in if-statements. Every time your code is indented another level, you are adding another piece of context that must be kept track of mentally while reading the code.

Let's look at a simple function that doesn't use the pattern.

1function update($contact, $data) {
2 if (valid($data)) {
3 $contact->update($data);
4 }
5}

With such a simple example it may not seem like a big deal (and it probably isn't), but let's see what refactoring to a guard clause looks like anyway.

1function update($contact, $data) {
2 if (! valid($data)) {
3 return;
4 }
5 
6 $contact->update($data);
7}

This is the essence of the guard clause. Reducing indentation, which reduces complexity and unnecessary context, and increases visibility of what the function is meant to do.

Let's get right into a more complex piece of code to really see where it shines.

1if (! is_null($subscribed)) {
2 if ($email = $contact->email) {
3 $updated = Contact::query()
4 ->where('email', $email)
5 ->where('is_subscribed', ! $subscribed)
6 ->update([
7 'is_subscribed' => $subscribed,
8 ]);
9 
10 if ($updated) {
11 if ($subscribed) {
12 event(new Subscribed($email));
13 } else {
14 event(new Unsubscribed($email));
15 }
16 }
17 }
18}

What's awesome about the guard clause is we can take the code here, which, at some points, gets 4 if-statements deep, and reduce it to a single indentation.

The steps to do this are simple:

  1. Invert the if-statement to check for the opposite condition.
  2. Terminate the if-statement before the rest of the code with a return statement inside of it.
  3. Repeat.

The only time this isn't doable is if the if has an else or if there are elseif's.

Let's see one step at a time. First, we will take the if-statement in the first line and turn it into a guard clause.

1if (is_null($subscribed)) {
2 return;
3}
4 
5if ($email = $contact->email) {
6 $updated = Contact::query()
7 ->where('email', $email)
8 ->where('is_subscribed', ! $subscribed)
9 ->update([
10 'is_subscribed' => $subscribed,
11 ]);
12 
13 if ($updated) {
14 if ($subscribed) {
15 event(new Subscribed($email));
16 } else {
17 event(new Unsubscribed($email));
18 }
19 }
20}

Instead of continuing when $subscribed is not null, we terminate when it is null. Mentally, we can now discard this information so we can focus on what the code is doing. However, once again, the code after our new guard clause is wrapped entirely in an if-statement. Let's repeat the process.

1if (is_null($subscribed)) {
2 return;
3}
4 
5if (! ($email = $contact->email)) {
6 return;
7}
8 
9$updated = Contact::query()
10 ->where('email', $email)
11 ->where('is_subscribed', ! $subscribed)
12 ->update([
13 'is_subscribed' => $subscribed,
14 ]);
15 
16if ($updated) {
17 if ($subscribed) {
18 event(new Subscribed($email));
19 } else {
20 event(new Unsubscribed($email));
21 }
22}

We've reduced another level of indentation! Now if the contact doesn't have an email, we won't subscribe them. Terminated. We are getting to the core of what this function is actually accomplishing and less focused on what the edge cases are. So much easier to read.

If you look at line 16 above, you'll see another chunk of code inside a single if-statement. You guessed it--we are adding a guard clause.

1if (is_null($subscribed)) {
2 return;
3}
4 
5if (! ($email = $contact->email)) {
6 return;
7}
8 
9$updated = Contact::query()
10 ->where('email', $email)
11 ->where('is_subscribed', ! $subscribed)
12 ->update([
13 'is_subscribed' => $subscribed,
14 ]);
15 
16if (! $updated) {
17 return;
18}
19 
20// a little extra sugar for fun ;)
21$event = $subscribed ? Subscribed::class : Unsubscribed::class;
22$event::dispatch($email);

And look at that. We've completely reduced a 4x indented block of code to a single indentation. In my opinion, our result is much more readable.

Since I discovered this pattern I've found places to refactor to it or use it just about every day.

I hope you find it as useful as I do. Good luck!