Lesson 12 of 45 · Principles of Good Object Design
Guard Clauses and Defensive Programming
The pyramid of doom
You've read this method, or one shaped exactly like it:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Money;
use App\Booking\Exceptions\InactiveGuest;
use App\Booking\Exceptions\MissingPaymentMethod;
use App\Booking\Exceptions\RoomNotAvailable;
use App\Booking\Exceptions\SuspiciousActivity;
use App\Booking\Guest;
use App\Booking\GuestCount;
use App\Booking\Room;
use InvalidArgumentException;
final class RequestReservationService
{
public function __construct(
private Reservations $reservations,
private FraudCheck $fraudCheck,
) {}
public function requestReservation(Guest $guest, Room $room, DateRange $stayDates, GuestCount $guestCount, Money $quotedPrice): Reservation
{
if ($guest !== null) {
if ($guest->isActive()) {
if ($room->isAvailableFor($stayDates)) {
if ($guest->hasPaymentMethod()) {
if (!$this->fraudCheck->isSuspicious($guest)) {
// The actual logic, finally, five levels deep
$reservation = Reservation::request($guest->id, $room->id, $stayDates, $guestCount, $quotedPrice);
$this->reservations->save($reservation);
return $reservation;
} else {
throw new SuspiciousActivity($guest->id);
}
} else {
throw new MissingPaymentMethod($guest->id);
}
} else {
throw new RoomNotAvailable($room->id, $stayDates);
}
} else {
throw new InactiveGuest($guest->id);
}
} else {
throw new InvalidArgumentException('Guest is null');
}
}
}(Guest is the class from the Immutable Objects lesson, and the example assumes it also has isActive() and hasPaymentMethod(). Room has a public id and an assumed isAvailableFor() method. The four exceptions in App\Booking\Exceptions are plain domain exceptions that carry the ids they are given and are not shown. FraudCheck is an assumed collaborator, Reservations is a repository interface with a save() method, and Reservation::request is the named constructor from the Named Constructors lesson.)
The actual logic is three lines. Everything else is the staircase climbing down to it. Reading the method means tracking five levels of indentation, each one with its else branch on the way back up.
The fix is one of the smallest, oldest tricks in the book: guard clauses. Flip the conditions. Return or throw early when something is wrong. Let the happy path live at the top of the indentation, where the eye expects it.
This lesson is about that habit, why it pays off, and how it relates to the broader question of defensive programming, which is its own topic.
What guard clauses are
A guard clause is an early check at the start of a method that bails out (returns, throws, or otherwise short-circuits) when a precondition isn't met.
The same method, with guard clauses:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Money;
use App\Booking\Exceptions\InactiveGuest;
use App\Booking\Exceptions\MissingPaymentMethod;
use App\Booking\Exceptions\RoomNotAvailable;
use App\Booking\Exceptions\SuspiciousActivity;
use App\Booking\Guest;
use App\Booking\GuestCount;
use App\Booking\Room;
final class RequestReservationService
{
public function __construct(
private Reservations $reservations,
private FraudCheck $fraudCheck,
) {}
public function requestReservation(Guest $guest, Room $room, DateRange $stayDates, GuestCount $guestCount, Money $quotedPrice): Reservation
{
if (!$guest->isActive()) {
throw new InactiveGuest($guest->id);
}
if (!$room->isAvailableFor($stayDates)) {
throw new RoomNotAvailable($room->id, $stayDates);
}
if (!$guest->hasPaymentMethod()) {
throw new MissingPaymentMethod($guest->id);
}
if ($this->fraudCheck->isSuspicious($guest)) {
throw new SuspiciousActivity($guest->id);
}
$reservation = Reservation::request($guest->id, $room->id, $stayDates, $guestCount, $quotedPrice);
$this->reservations->save($reservation);
return $reservation;
}
}Same logic. Same exceptions. The pyramid is gone. The reader scans top-to-bottom: "these are the things that can go wrong"; "and here's what happens when nothing goes wrong". The shape of the method matches the shape of the work.
Notice what else changed. The null check on $guest disappeared, because in this codebase the type system already says $guest is never null. The else branches disappeared, because the throws end the method early.
Why this matters
A few concrete benefits of writing methods this way:
Less to hold in your head. Each guard is a self-contained check. The reader can dismiss it ("not the case I'm tracing") and move on. The pyramid version makes the reader keep all five conditions in scope while looking for the one piece of real logic at the bottom.
Failure cases become locatable. Each business rule that prevents the happy path has a named exception, in a clear location, near the top of the method. Searching for "where does
RoomNotAvailableget thrown?" is one grep, one match.The happy path stops hiding. In the pyramid, finding "what does this method actually do?" requires scrolling. In the flat version, the answer is at the bottom, at one indentation level, easy to read.
Refactors are cheaper. Adding a sixth check is one new guard at the top. In the pyramid version, you have to choose where to insert it, and the rest of the structure has to be re-indented around it.
Reading is most of the job, and most of the cost of a change is the reading. Guard clauses cut the reading a method needs.
What about a single return?
A common objection: "shouldn't a method have one return statement?"
In modern PHP, with type hints, exceptions and early returns, multiple return statements (or throws) at the top of a method are clearer than a single return at the bottom of a nested staircase.
Use as many early exits as the method needs to express its preconditions. Save the single-final-return discipline for the inside of long, complex calculations where the multi-return version would genuinely make the math hard to follow. For most methods, that situation doesn't apply.
Defensive programming
Guard clauses are part of a broader habit called defensive programming: writing code that anticipates and handles invalid inputs, unexpected states, and runaway conditions.
The basic idea sounds reasonable: don't trust your inputs. Check them. Fail fast when something is wrong. Don't let a bad value silently propagate.
The basic idea is also wildly over-applied. A method that checks every parameter for null when the type system already forbids null, validates ranges that already passed the request validator, asserts invariants the caller already enforced... that method is paranoid. Every check has a cost: more code to read, more branches to test, more places for bugs to hide.
The honest version of defensive programming has two rules:
1. Defend at boundaries. Trust internally.
The places to defend are the places where you don't control the input:
HTTP request handlers (the user can send anything).
Webhook endpoints (the third party can send anything).
File system reads (the file might not exist, might be malformed).
Third-party API responses (the vendor might change shape).
Database boundaries when you don't control the schema.
Inside your own code, where the type system, value objects, and data transfer objects already constrain inputs, defending again is duplication of constraints that are already enforced.
2. Fail loudly, don't fail silently.
If something is wrong and you can't recover, throwing is better than returning null, returning a default, or logging and continuing. Silent failures show up in production as data corruption, missing updates, or downstream bugs that are impossible to trace. Loud failures show up as exceptions in your monitoring, with stack traces that point at the cause.
The PHP-specific picture
Type hints reduce the need for guards. A parameter typed Guest $guest cannot be null. The check if ($guest !== null) is dead code. PHP throws a TypeError when null is passed. Lean on the type system; don't reimplement it in conditionals.
Value objects do most of the validation work. If your Money constructor refuses negative values, methods that take Money don't need to check for negatives. The Value Objects lesson was the prerequisite. Once value objects validate at construction, downstream methods can trust the value. The strongest guard is a type that makes the bad case impossible to construct: a final readonly class EmailAddress that refuses invalid addresses beats five guards in five methods that each check whether a string looks like an email.
Form requests handle input validation at the boundary. Laravel's FormRequest classes are the right place for "the user sent this, is it well-formed?" checks. Don't repeat those checks inside the use case. Use a data transfer object to carry the validated data inward, and trust it.
Throw domain exceptions, not generic ones. throw new InactiveGuest($guest->id) is more useful than throw new \Exception('guest not active'). Domain exceptions become part of the API of the use case. They can be caught specifically. They can be rendered to specific HTTP responses. Later lessons get into this in detail; for now, prefer named exceptions over generic ones.
match (true) is another option when every guard throws. Since PHP 8.0, throw is an expression, so each guard can be one arm of a match. The arms run in order and stop at the first one that matches, the same as the stack of ifs:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Money;
use App\Booking\Exceptions\InactiveGuest;
use App\Booking\Exceptions\MissingPaymentMethod;
use App\Booking\Exceptions\RoomNotAvailable;
use App\Booking\Exceptions\SuspiciousActivity;
use App\Booking\Guest;
use App\Booking\GuestCount;
use App\Booking\Room;
final class RequestReservationService
{
public function __construct(
private Reservations $reservations,
private FraudCheck $fraudCheck,
) {}
public function requestReservation(Guest $guest, Room $room, DateRange $stayDates, GuestCount $guestCount, Money $quotedPrice): Reservation
{
match (true) {
!$guest->isActive() => throw new InactiveGuest($guest->id),
!$room->isAvailableFor($stayDates) => throw new RoomNotAvailable($room->id, $stayDates),
!$guest->hasPaymentMethod() => throw new MissingPaymentMethod($guest->id),
$this->fraudCheck->isSuspicious($guest) => throw new SuspiciousActivity($guest->id),
default => null,
};
$reservation = Reservation::request($guest->id, $room->id, $stayDates, $guestCount, $quotedPrice);
$this->reservations->save($reservation);
return $reservation;
}
}It has two traps the ifs don't. Leave out default => null and a valid request throws UnhandledMatchError, so the bug fires on exactly the input that should succeed. And match compares with ===, so an arm only fires when its condition is exactly true. A method that returns a truthy value like 1 instead of a bool skips its guard without a word. Use it when every guard throws and every condition is a method typed : bool. Otherwise, write the ifs.
Avoid asserts for business rules. PHP's recommended production config, php.ini-production, sets zend.assertions = -1, which skips assert() calls entirely. Anything that's an actual business rule should throw a real exception, not an assertion. Asserts are for invariants that should be impossible to violate; if you can't trust them to run in production, don't use them for things that matter.
Pitfalls
Paranoia in internal code. A method that takes a typed Guest and starts with if ($guest === null) throw ..., if (!$guest->id instanceof GuestId) throw ..., and if ($guest->email()->value === '') throw ... is defending against impossibilities. The parameter type rules out null, the property type rules out a wrong id, and EmailAddress refuses an empty address when it's built.
Defensive returns instead of defensive throws. Returning null, false, [], or a "default" object when something is wrong is the worst of both worlds: the caller has to remember to check, and most callers won't. The bug surfaces somewhere else, far from the cause. Throw, or return a Result object that forces the caller to handle the failure.
Catch-and-swallow. try { ... } catch (\Throwable $e) { /* nothing */ } is the opposite of defensive programming. It's actively hostile to the reader. If you don't know what to do with an exception, let it propagate. If you have something specific to do (log, retry, fall back), do that, and only catch the specific exception type the case applies to.
Validating the same thing in four places. If the form request validates the email, the data transfer object validates it again, the value object validates it again, and the model validates it again, two of those are wasted work. The form request checks it so the user gets a readable error message. The EmailAddress value object enforces it for every other way in, like a webhook or a console command. The data transfer object and the model can trust the type.
Comments instead of guards. // caller must ensure $foo is not empty is not a guard. Either enforce it (throw if empty) or design it out (require a non-empty type). Comments age and rot; guards run.
A practical sequence
When you find yourself writing a method:
Write the happy path first, as if all preconditions are met.
Now think about what would make the happy path invalid. List those conditions.
For each one, add a guard clause at the top of the method that throws (or returns early) with a named exception or result.
Read the method top to bottom. The shape should be: a stack of "no, not this case" guards, then the work.
If the stack of guards gets too tall, that's a design signal. Either the method is doing too much (split it), or several of those guards belong on the value objects coming in (push them down), or a precondition is really a separate operation that should have happened first (move it).
The one thing to remember
Flatten your methods and throw early when something is wrong. Trust your types, and defend at boundaries, not in the middle. The shape of a method should match the shape of the work it does, with the failure cases on the outside and the happy path in the center.
Related Links
- Replace Nested Conditional with Guard ClausesFowler's refactoring catalog entry for the exact technique this lesson teaches, with a short before-and-after sketch.
- Fail FastJim Shore's IEEE Software article (hosted on Fowler's site) on why software should raise errors as close to their cause as possible instead of letting them travel.
- Exceptions and talking back to the userMatthias Noback on using exceptions to protect an object's state rather than as a stand-in for user-facing error messages.
- Throwable errorsThe PHP manual page on throw, catch, and finally, the mechanics behind throwing early at a boundary.