design patterns · behavioral
Null Object
Provides a default object with do-nothing behavior instead of null, eliminating null checks throughout code.
Pattern
Overview
Intent
Provide a default object with do-nothing (no-op) behavior instead of using null, to avoid null checks and NullPointerExceptions.
Real-World Analogy
Silent mode on a phone - the speaker interface is still there, all calls succeed, but output is nothing. No need to check "is speaker enabled?" before calling play().
Instead of returning null when an object is absent and forcing every caller to null-check, return a NullObject that implements the same interface with do-nothing behavior.
Both RealObject and NullObject implement the same interface. NullObject methods do nothing or return safe defaults. Client code calls methods on the interface without checking for null - the NullObject silently absorbs the calls.
When to use
Optional dependencies (logging, optional listeners), default implementations for optional strategies, avoiding defensive null checks in client code.
When not to
When absence is an error condition that should be reported. When the caller must distinguish between "object present" and "object absent".
Participants
Key Insights
- NullObject is a specialization of Strategy - it is the "do nothing" strategy
- Java Optional<T> is a modern alternative that makes absence explicit at the type level
- NullObject is preferable when many callers use the object - avoids repeated Optional.isPresent() checks
- A NullLogger (logs nothing) is the classic example in production systems