Posted on January 14, 2019
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:
1 2 3 4 5 6 7 8 9 |
function doThing() { var $thing = 'default'; if (someCondition()) { $thing = 'special case'; } return $thing; } |
Using a Guard Clause we can simplify it to:
1 2 3 4 5 6 7 |
function doThing() { if (someCondition()) { return 'special case'; } return 'default'; } |
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.
Recent Comments