Replace Nested Conditional with Guard Clauses
Replace nested conditionals with guard clauses.
“A method has conditional behavior that does not make clear the normal path of execution.”
Fail fast, return early.
graph LR
A[Deeply Nested Ifs] -->|Refactoring| B[Flat List of Checks (Guard Clauses)]
When to apply (Smells)
- Arrow Code: Code shape looks like an arrow because of indentation.
- Conditional Complexity: Hard to see the “happy path”.
Motivation
- Readability: Isolate the special cases check them, and return immediately.
- Flatness: Reduces nesting levels.
Mechanics (Steps)
- Identify a check that causes a return or throw.
- Make it a guard clause (if condition return).
- Remove the else block.
Explanation
Problem
if (dead) return; else { if (critical) ... }
Solution
if (dead) return; if (critical) ...
Real world analogy
Bouncers at a club. They check your ID at the door (Guard Clause). They don’t let you walk all the way to the bar before checking if you are 21.
Pros and Cons
| Pros | Cons |
|---|---|
Code example
Typescript
Before
After
PHP
Before
After