Member-only story
Refactoring: Guard Clauses
A technique to be a better developer

“In computer programming, a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question. Regardless of which programming language is used, guard code or a guard clause is a check of integrity preconditions used to avoid errors during execution.” — Wikipedia
The main problems that appear in code in which the guard clauses technique is not applied are the following:
- Excessive indentation — Excessive use of the control structure if nested means that there is a high level of indentation that makes code reading difficult.
- Relationship between if-else — When there is a large number of separate code fragments between if-else, which are conceptually related to each other, it’s necessary to perform the code reading by jumping between the different parts.
- Mental effort— A consequence of the different jumps in the source code causes an extra effort to be generated in the generation of code.
Practical Applications
The practical application of a guard clause is the following case:

In this case, and most of the time, you must reverse the logic to avoid using the reserved word else
. The previous code would be rewritten as follows:

Therefore, the particular cases that cause an exit of the method would be placed at the beginning of the method and act as guards in a way that avoids continuing through the satisfactory flow of the method.
In this way, the method is easy to read since the particular cases are at the beginning of the same and the case of satisfactory flow use is the body of the method.
There are detractors of the guard clauses who indicate that there should only be a single exit point in each method and with this technique, we find several exit points. It…