Readable Functions: Guard Clause

Guard Clauses are one of my favorite little tricks that allow simplifying code. A guard clauses is an if statement with a return in it. Consider the following code:

Using a Guard Clause we can simplify it to:

The if statement in this simplified code is a Guard Clause. You can have multiple Guard Clauses in a function.

The simplification removes ALL the state in the function, including the nasty and completely not needed mutation in the first form of the code. You can read the new code sequentially, and the code after the Guard Clause is not polluted by extra complexity arising from the special case.

This post is part of the Readable Functions series which contains tricks like this one and two general principles: Minimize State and Do One Thing.

One Comment on “Readable Functions: Guard Clause

  1. Pingback: Readable Functions: Minimize State - Entropy Wins

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.