design patterns ·
Null Object
Provides a default object with do-nothing behavior instead of null, eliminating null checks throughout code.
Theory
Explanation
Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.
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".
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