Lesson 21 of 45 · Behavior and Variation
The Null Object Pattern
The null check tax
You write a class that takes an optional logger:
<?php
declare(strict_types=1);
namespace App\Reservations;
use Psr\Log\LoggerInterface;
final readonly class CheckInGuest
{
public function __construct(private ?LoggerInterface $logger = null) {}
public function __invoke(Reservation $reservation): void
{
if ($this->logger !== null) {
$this->logger->info('reservation.check_in.started', ['id' => $reservation->id->value]);
}
// ... check the guest in ...
if ($this->logger !== null) {
$this->logger->info('reservation.check_in.completed', ['id' => $reservation->id->value]);
}
}
}Reservation here is trimmed to id (a ReservationId with a string value) plus the totalPrice, stayDates and cancellationPolicyType properties from the Strategy Pattern lesson.
Two if blocks, identical structure, doing the same defensive dance: "if a logger was provided, use it; otherwise, do nothing". The actual work of the method is buried between them.
Now imagine the same pattern across a codebase: a ?Mailer, a ?Voucher, a ?Discount, a ?LoyaltyProgram. Every consumer of every optional collaborator has to remember the null check, and the codebase fills up with noise that has nothing to do with what the methods are about. The consumer that forgets fails with Error: Call to a member function info() on null, and only when no logger was passed.
The Null Object Pattern makes that whole class of code disappear. Instead of asking "is this thing here?" before every use, you arrange for the absence of the thing to be its own object: a "do nothing" object that satisfies the same interface. Consumers can call methods on it without checking. The methods just don't do anything visible.
What the Null Object Pattern is
A null object is a class that implements an interface and does nothing, or returns a neutral value such as zero or an empty list. It satisfies the contract syntactically; semantically, it's a stand-in for "no real implementation".
The shape:
An interface that some collaborator implements.
A real implementation that does the work.
A null object implementation that satisfies the interface but takes no action or returns a neutral value.
The container (or factory) provides the null object whenever the absence applies.
A worked example
The logger from above, with a null object. The psr/log package (PSR-3, the PHP-FIG logging standard) already ships one, Psr\Log\NullLogger, which implements LoggerInterface and discards every call. The consumer becomes:
<?php
declare(strict_types=1);
namespace App\Reservations;
use Psr\Log\LoggerInterface;
final readonly class CheckInGuest
{
public function __construct(private LoggerInterface $logger) {}
public function __invoke(Reservation $reservation): void
{
$this->logger->info('reservation.check_in.started', ['id' => $reservation->id->value]);
// ... check the guest in ...
$this->logger->info('reservation.check_in.completed', ['id' => $reservation->id->value]);
}
}The optional parameter is gone. The null checks are gone. The signature is honest: this class needs a logger. If the caller doesn't have a real one, they construct it with new CheckInGuest(new \Psr\Log\NullLogger()) and the calls are silently absorbed.
More cases
A "no cancellation policy" policy for legacy reservations:
Some reservations were imported from a legacy system that didn't capture a cancellation policy, so their cancellationPolicyType is null. CancellationPolicy is the strategy interface from the Strategy Pattern lesson. The null object is one more implementation:
<?php
declare(strict_types=1);
namespace App\Reservations\Cancellation;
use App\Billing\Money;
use App\Reservations\DateRange;
use DateTimeImmutable;
final readonly class NullCancellationPolicy implements CancellationPolicy
{
public function refundFor(Money $totalPrice, DateRange $stayDates, DateTimeImmutable $now): Money
{
return Money::zero($totalPrice->currency);
}
}Rather than scattering if ($reservation->cancellationPolicyType !== null) checks everywhere, the CancellationPolicyFactory from the Strategy Pattern lesson gets a fifth dependency and a null arm that returns the null object. This class replaces that version:
<?php
declare(strict_types=1);
namespace App\Reservations\Cancellation;
use App\Reservations\CancellationPolicyType;
use App\Reservations\Reservation;
final readonly class CancellationPolicyFactory
{
public function __construct(
private FlexibleCancellation $flexible,
private ModerateCancellation $moderate,
private StrictCancellation $strict,
private NonRefundableCancellation $nonRefundable,
private NullCancellationPolicy $none,
) {}
public function for(Reservation $reservation): CancellationPolicy
{
return match ($reservation->cancellationPolicyType) {
CancellationPolicyType::Flexible => $this->flexible,
CancellationPolicyType::Moderate => $this->moderate,
CancellationPolicyType::Strict => $this->strict,
CancellationPolicyType::NonRefundable => $this->nonRefundable,
null => $this->none,
};
}
}Every caller of for() now gets a CancellationPolicy. The null object refunds zero, which is what the old RefundCalculator in the Strategy Pattern lesson returned for these reservations, and the rest of the code stops caring whether the policy was set. RefundableReservation from the Specification Pattern lesson now returns false for them instead of throwing UnhandledMatchError.
NonRefundableCancellation also refunds zero, so the null arm could point at it. A separate class keeps two facts apart: "this reservation has a non-refundable policy" and "nobody recorded a policy". A report can count the legacy reservations, and a later decision to refund them changes one class without touching non-refundable bookings.
This connects back to the asking pattern from the Tell, Don't Ask lesson. The null check is asking ("is this here?") and acting on the answer. The null object replaces that with telling ("calculate the refund for this reservation"), where the policy's response to being asked happens to be "refund zero".
A "no audit" auditor for tests:
(AuditEvent is a small value class of the app's own, not shown.)
<?php
declare(strict_types=1);
namespace App\Audit;
interface AuditLogger
{
public function record(AuditEvent $event): void;
}<?php
declare(strict_types=1);
namespace App\Audit;
final readonly class NullAuditLogger implements AuditLogger
{
public function record(AuditEvent $event): void { /* nothing */ }
}In production, a real auditor writes to the audit table. In tests that don't care about audit behavior, the binding swaps in NullAuditLogger and the tests don't have to mock anything.
When it earns its place
The pattern is right when:
The consumer would otherwise write defensive null checks that have no business-meaning, just plumbing.
The "absence" is itself a domain concept (no cancellation policy attached, no loyalty tier set) and "do nothing" is a sensible default for that absence.
It doesn't earn its place when:
The consumer needs to react differently to "no thing" vs "real thing". If the calling code wants to know whether a logger was provided, the null object defeats the purpose.
The interface is huge. Implementing 40 methods that all return
nullor do nothing is a maintenance hazard. Either split the interface (the Interface Segregation Principle) or skip the pattern.
When the caller does need to react, make the absence visible instead. Languages with Option types (Rust's Option, Haskell's Maybe) or checked nullable types (Kotlin's String?) won't let the caller use the value until it has handled the missing case, short of an explicit escape hatch like Rust's unwrap(). In PHP the closest equivalent is a nullable return type, which PHPStan checks from level 8. A null object removes the check, so it only fits when no caller needs to know.
Pitfalls
Hiding real bugs behind null objects. A NullPaymentGateway that silently approves every charge loses money in production. Null objects belong where the absence is genuinely a "do nothing" case. They don't belong where the absence is a real problem.
Null objects that keep state. A null object should be stateless. A logger that counts its calls is a spy, so name it and use it as one.
Over-implementing. A null object only needs to satisfy the interface. Most have no state and no dependencies, so they can be final readonly class with no constructor. The simpler it is, the safer it is to bind.
Using null objects to skip required behavior. "We don't need to send notifications in tests, let's bind a NullNotifier" is fine. "We don't need to enforce permissions in this admin tool, let's bind an always-allow guard" is dangerous. The pattern should not be a backdoor around critical behavior.
Confusing null objects with empty fakes. A test fake (InMemoryRepository) is an implementation that genuinely tracks state and answers correctly for the test's scope. A null object is a stand-in that does nothing. They look similar at the call site and serve different purposes. The Test Doubles lesson draws the line: a null object passed only to satisfy a constructor is a dummy, and an in-memory repository is a fake.
PHP-specific notes
Container bindings. The natural place to wire null objects is the container, in environments where the real thing isn't available. Laravel does this in tests: the default phpunit.xml sets BROADCAST_CONNECTION=null, which swaps in NullBroadcaster. Setting LOG_CHANNEL=null does the same for logs: that channel discards every entry through Monolog's NullHandler. The same file sets MAIL_MAILER=array, and that one is a fake: the array mailer keeps every message so a test can read it back.
Be explicit in naming. NullLogger, NullCancellationPolicy, NullAuditLogger. The name should make it obvious that this is the absence-shaped implementation. Avoid generic names like DefaultLogger (which suggests sensible defaults, not "do nothing").
The one thing to remember
When you find yourself writing if ($x !== null) { $x->doSomething(); } repeatedly across a codebase for an optional collaborator, and no caller needs to tell the real thing from the missing one, the absence wants to be a class. A small "do nothing" implementation of the interface, bound where appropriate, removes every one of those checks and lets the consumer code focus on what it's actually doing.
Related Links
- Null object pattern (Wikipedia)An overview of the pattern and why it removes null checks by giving absence its own class.
- NullLogger.php (php-fig/log)The actual source of PSR-3's NullLogger, the ready-made null object this lesson points to.
- Object Interfaces (PHP Manual)The PHP manual page on interfaces, the contract a null object and its real counterpart both implement.