Null Object Pattern
An object that implements the interface and does nothing, so callers stop checking for null. Know when absence should be invisible, when it must be loud, and how the pattern differs from Optional and nullable types.
Overview
The Null Object pattern replaces 'nothing' with an object that has the right interface and safe, empty behavior. Instead of every caller writing if logger is not None: logger.log(...), the code is given a NullLogger whose log does nothing, and the check disappears from every call site.
The pattern is credited to Bobby Woolf's paper 'Null Object' in *Pattern Languages of Program Design 3* (1998), and Martin Fowler's refactoring catalog lists Introduce Null Object as the older name of Introduce Special Case: a class that stands in for a special value and answers with defaults. Tony Hoare, who added the null reference to ALGOL W in 1965, called it his billion-dollar mistake in a 2009 talk; this pattern is one of the ways code avoids handing null around.
Interviewers want to see the mechanism (same interface, empty methods), one judgment call (a missing logger may be silent; a missing payment gateway must not be), and the comparison with the language tools that make absence visible instead of invisible: Optional in Java, nullable types in Kotlin.
The mechanism
The pattern has four pieces, and the caller only ever sees the first one.
- The interface: what callers rely on, here log(message).
- The real object: does the work.
- The null object: implements every method with a safe no-op or a neutral value, such as an empty list, zero or false.
- The caller: depends on the interface and never asks which one it holds.
Interview questions
- Explain the Null Object pattern with a concrete example.
- When should you use a Null Object and when Optional or a nullable type?
- What are the risks of the Null Object pattern, and how do you limit them?
- How does the Null Object pattern relate to the Interface Segregation Principle?
- Show a Null Object that returns neutral values, not just no-ops.
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio