guard-clauses
Replace nested conditional logic with early returns (guard clauses) to reduce nesting and clarify intent.
SKILL.mdskills/code-quality/guard-clauses/SKILL.md
GitHubReplace Nested Conditional with Guard Clauses
Deep nesting hides the main logic. Guard clauses handle special/edge cases early and return immediately, leaving the happy path flat and prominent.
When to Use
- Method has a deeply nested
if/else if/elsechain - One branch is the normal case; others are exceptions or edge cases
- Readers must scroll through guards to find core logic
- Cyclomatic complexity is high
How to Apply
- Identify exceptional conditions (null, invalid state, permissions)
- For each: add an early
return(orthrow) at the top of the method - Remove the now-redundant outer
else - Flatten the remaining code
- Run tests
Example
// Before
function getPayAmount(employee: Employee): number {
if (employee.isSeparated) {
return 0;
} else {
if (employee.isRetired) {
return retiredAmount(employee);
} else {
return normalPayAmount(employee);
}
}
}
// After
function getPayAmount(employee: Employee): number {
if (employee.isSeparated) return 0;
if (employee.isRetired) return retiredAmount(employee);
return normalPayAmount(employee);
}