Guard clauses in C#: flatten nesting, keep the behavior
Guard clauses turn nested conditionals into a flat list of early exits. One refactor took nesting from 5 to 1 while cyclomatic complexity stayed at 6.
Rewriting the method below with guard clauses took its nesting depth from 5 to 1 and its cognitive
complexity from 20 to 5, while its cyclomatic complexity stayed at 6. To read this version, you scroll down
to find where the real work happens and then back up to work out which else belongs to which if.
public static string Review(Refund request, DateOnly today)
{
string result;
if (request.Order != null)
{
if (request.Order.PaidAt != null)
{
if (!request.Order.Refunded)
{
if (request.Order.PaidAt.Value.AddDays(30) >= today)
{
if (request.Amount <= request.Order.Total)
{
result = "approved";
}
else
{
result = "amount exceeds order";
}
}
else
{
result = "window closed";
}
}
else
{
result = "already refunded";
}
}
else
{
result = "not paid";
}
}
else
{
result = "unknown order";
}
return result;
}Each failure is written far from the condition that causes it. The check for a missing order is at the top and its message is more than 30 lines down. To understand the rejection for an already refunded order, you hold three conditions in your head and then match braces.
A guard clause handles a condition that stops the method and exits immediately, so everything after it can assume that condition is gone. The move works the same in any language with an early return. Martin Fowler catalogs the move as Replace Nested Conditional with Guard Clauses. For this method, the result is:
public static string Review(Refund request, DateOnly today)
{
var order = request.Order;
if (order == null) return "unknown order";
if (order.PaidAt == null) return "not paid";
if (order.Refunded) return "already refunded";
if (order.PaidAt.Value.AddDays(30) < today) return "window closed";
if (request.Amount > order.Total) return "amount exceeds order";
return "approved";
}Reaching that version safely takes more care than the final code suggests.
Same decisions, different reading path
Nested: the answer sits at the bottom of the stairs
if (order exists)
if (paid)
if (not refunded)
if (inside window)
if (amount fits)
approved
Guarded: each failure leaves as soon as it is known
if (no order) return
if (not paid) return
if (refunded) return
if (window closed) return
if (amount too big) return
approved
- Cyclomatic complexity
- 6 to 6
- Max nesting depth
- 5 to 1
- Cognitive complexity
- 20 to 5
A refactor changes structure and leaves behavior alone, and you need something that can tell you if it did not. If tests already cover the method, run them. If they do not, keep the old version under a new name for an hour and compare the two directly across inputs that sit on every decision:
DateOnly?[] paidDates = [null, today.AddDays(-31), today.AddDays(-30), today.AddDays(-29), today];
bool[] refundedFlags = [false, true];
decimal[] amounts = [0m, 99.99m, 100.00m, 100.01m];
var requests = new List<Refund>();
foreach (var amount in amounts)
{
requests.Add(new Refund(null, amount));
foreach (var paid in paidDates)
foreach (var refunded in refundedFlags)
requests.Add(new Refund(new Order(paid, refunded, 100.00m), amount));
}
var differences = requests.Count(r => ReviewOld(r, today) != Review(r, today));The inputs include the exact last day of the window and the exact order total, because a boundary is where a slip in a comparison shows up. For this method that gives 44 combinations, every one of the six outcomes appears, and after the refactor the count of differences is 0. Delete the old copy once you have promoted the useful cases to real tests.
Work one level at a time and run the comparison after each step.
Start with the outermost if. Its else is the short branch, so invert the condition, move that branch
to the top and return from it:
if (request.Order == null)
{
result = "unknown order";
return result;
}
if (request.Order.PaidAt != null)
{
// everything else, now one level shallower
}Repeat for the next level, and the next. Each pass removes one indent from everything below it. When no
else remains, the result variable has become pointless, since every assignment sits right next to a
return, so replace those pairs with direct returns and delete the variable. Introducing order as a
local comes last. A local copy of the reference is safe at any point, as nothing dereferences it before the
guard.
Inverting a comparison incorrectly. The opposite of >= is <, but in the moment <= looks just as
plausible. Changing the window guard to AddDays(30) <= today altered the result for 4 of the
44 inputs, all of them on the last valid day. A customer on day 30 is now told the window has closed. A
comparison run with only midpoint dates would have reported no differences at all. For compound conditions
the same care applies to De Morgan's laws: the opposite of a && b is !a || !b, and a condition with
several terms is often clearer split into two guards.
Reordering guards. While the guards are in a list, it is tempting to sort them by importance. But the order of checks is behavior when more than one condition can be true at once. Swapping the refund guard and the window guard changed the output for 4 of the 44 inputs. An old, refunded order went from "already refunded" to "window closed", which is a different message to a customer and possibly a different branch in a caller that switches on the result. If you want a new order, make it a separate commit, because that one is a behavior change and should be reviewed as one.
Swapping two guards changed the answer for 4 of 44 inputs. Writing
<=for<in one inversion changed 4 more.
A small syntax-tree walker over both versions, counting decisions and the deepest level of nested ifs,
produced this table. Cognitive complexity is worked by hand below.
| Metric | Nested | Guarded |
|---|---|---|
| Cyclomatic complexity | 6 | 6 |
| Max nesting depth | 5 | 1 |
| Cognitive complexity | 20 | 5 |
| Lines in the method | 41 | 11 |
| Return statements | 1 | 6 |
Cyclomatic complexity does not move. It counts decisions, plus one, and both versions make the same five. As the cyclomatic complexity post explains, that number is mostly a measure of how many paths need testing, and you still have six. Guard clauses make a method easier to read and leave the test burden where it was.
Nesting and cognitive complexity are the metrics that register the change. Under the
Cognitive Complexity rules from SonarSource, each
if costs one plus its current nesting level, and each else costs one. The nested version scores
1 + 2 + 3 + 4 + 5 = 15 for the ifs and 5 for the elses, for a total of 20. The guarded version has five
ifs at nesting zero, for a total of 5. The paper explicitly adds nothing for an early return, on the grounds
that it can often make code clearer. That is one team's model of readability, not a measured law.
The C# refactoring exercises gate on the same kinds of measurement. As How grading works describes, they check method length, cyclomatic complexity, nesting depth and duplicate blocks against explicit limits, all on top of tests that confirm behavior did not change.
Manual cleanup. An early return skips whatever comes after it, and that includes a release written at the bottom of the method.
await _gate.WaitAsync(ct);
if (_pending.Count == 0) return; // the gate is never released
Send(_pending.Dequeue());
_gate.Release();Every later caller now waits forever. Put the acquired resource in using or try/finally before adding
any exit, and the guards become safe again.
Work done before the guard. A method that updates a status, then checks a condition and returns, leaves half-finished state behind. Guards belong before the first side effect. If a check can only happen after some work, an early return may be the wrong tool, and a transaction or a separate validation step may fit better.
Two ordinary outcomes. A guard says "this case is finished". When both branches are normal paths of equal
weight, an if/else shows that symmetry and a guard hides it:
if (isExpress)
{
return 5m + weight * 2m;
}
else
{
return 2m + weight;
}Some linters will ask you to drop that else. Keeping it is a reasonable choice, and so is a conditional
expression.
Exits buried deep in a long method. Guards at the top are easy to scan. A return inside a loop on line 80
is not, and reaching for early exits there usually means the method needs extracting. Short methods are what
make multiple returns comfortable.
Not every guard is the same kind of check. A null argument that should never occur is a programmer error, and
ArgumentNullException.ThrowIfNull
is the right response. "Window closed" is an expected answer that a caller has to handle, so it belongs in the
return value, as the Result pattern post discusses.
When the same validation guards open five different methods, stop copying them. A type that cannot hold an invalid value lets you check once at the edge, as in primitive obsession and value objects, and those guards disappear from everywhere else.
Practice what you just read
- Open in the editor: Flatten the Null Checks
Refactoring Easy Free, no account needed
Flatten the Null Checks
An address printer hiding at the bottom of four nested ifs.
More like this: C# refactoring exercises →