Null Object Pattern
Every codebase has collaborators that are sometimes missing. A guest at checkout has no loyalty account. A library is used by an application that never configured logging. A pricing rule exists for some products and not for others. The lazy way to model "missing" is null (or None, or undefined), and the price of that choice is paid at every call site: each caller has to remember to check, and the one that forgets crashes in production on the first guest who shows up.
The Null Object pattern takes a different route. Instead of handing out "nothing", you hand out a real object that implements the same interface and whose behaviour is the correct outcome for the missing case: a logger that drops messages, an account that earns no points and gives no discount, a discount policy that discounts by zero. Callers stop branching, because there is nothing to branch on.
It is not one of the 23 Gang of Four patterns. It was written up as a pattern in its own right in the 1990s (Bobby Woolf's chapter in Pattern Languages of Program Design 3 is the usual citation), and Martin Fowler describes the generalised version as Special Case in Patterns of Enterprise Application Architecture. It sits on this course's "beyond GoF" list because it shows up in almost every LLD round, usually without being named, and because it has a sharp edge: a do-nothing object can quietly swallow a failure that should have been loud. This page goes deeper than the grouped behavioral patterns overview, which does not cover it.
Intent
Represent the absence of a collaborator with an object that honours the collaborator's interface and does the neutral thing, so that clients can treat "present" and "absent" the same way and the decision about what "absent" means lives in exactly one place.
Three phrases in that sentence carry the weight:
- Honours the interface. A Null Object is a full substitute. It must satisfy the Liskov substitution principle: anything a client may rely on for a real implementation, it may rely on for the null one.
- The neutral thing. Each method returns the value that makes the overall computation come out right when the collaborator is absent: zero discount, an empty list, "no permission", a silent write. "Neutral" is a business decision, not a technical one.
- One place. The knowledge "a guest gets no discount and earns no points" is written once, in the null class, instead of being re-derived (and sometimes contradicted) at every
if (account != null).
The problem
Here is a small checkout. Customers may or may not belong to the loyalty programme, and the service may or may not have been given an audit log. Both are modelled as nullable.
import java.util.*;
final class LoyaltyAccount {
private long points;
LoyaltyAccount(long points) { this.points = points; }
long discountCents(long subtotal) { return subtotal * 5 / 100; }
void addPoints(long p) { points += p; }
long points() { return points; }
}
final class Checkout {
private final Map<String, LoyaltyAccount> accounts;
private final List<String> auditLog; // null means "no auditing"
Checkout(Map<String, LoyaltyAccount> accounts, List<String> auditLog) {
this.accounts = accounts;
this.auditLog = auditLog;
}
long pay(String customerId, long subtotal) {
LoyaltyAccount account = accounts.get(customerId); // null for guests
long discount = account != null ? account.discountCents(subtotal) : 0;
long total = subtotal - discount;
if (account != null) account.addPoints(total / 100);
if (auditLog != null) auditLog.add(customerId + " paid " + total);
return total;
}
long refund(String customerId, long amount) {
LoyaltyAccount account = accounts.get(customerId);
account.addPoints(-(amount / 100)); // forgot the check
if (auditLog != null) auditLog.add(customerId + " refunded " + amount);
return amount;
}
}
public class Before {
public static void main(String[] args) {
Map<String, LoyaltyAccount> accounts = new HashMap<>();
accounts.put("alice", new LoyaltyAccount(0));
Checkout checkout = new Checkout(accounts, null);
assert checkout.pay("alice", 10_000) == 9_500;
assert checkout.pay("guest-7", 10_000) == 10_000;
try {
checkout.refund("guest-7", 10_000);
throw new AssertionError("expected a crash");
} catch (NullPointerException expected) {
System.out.println("refund for a guest crashed: " + expected.getClass().getSimpleName());
}
}
}
class LoyaltyAccount:
def __init__(self, points: int = 0) -> None:
self._points = points
def discount_cents(self, subtotal: int) -> int:
return subtotal * 5 // 100
def add_points(self, p: int) -> None:
self._points += p
class Checkout:
def __init__(self, accounts: dict[str, LoyaltyAccount], audit_log: list[str] | None) -> None:
self._accounts = accounts
self._audit_log = audit_log # None means "no auditing"
def pay(self, customer_id: str, subtotal: int) -> int:
account = self._accounts.get(customer_id)
discount = account.discount_cents(subtotal) if account is not None else 0
total = subtotal - discount
if account is not None:
account.add_points(total // 100)
if self._audit_log is not None:
self._audit_log.append(f"{customer_id} paid {total}")
return total
def refund(self, customer_id: str, amount: int) -> int:
account = self._accounts.get(customer_id)
account.add_points(-(amount // 100)) # forgot the check
return amount
checkout = Checkout({"alice": LoyaltyAccount()}, None)
assert checkout.pay("alice", 10_000) == 9_500
assert checkout.pay("guest-7", 10_000) == 10_000
try:
checkout.refund("guest-7", 10_000)
raise AssertionError("expected a crash")
except AttributeError:
print("refund for a guest crashed")
Look at what the nullability costs:
- Every method repeats the same question.
payasks "is there an account?" twice and "is there a log?" once. Each new method that touches either collaborator has to ask again. - One forgotten check is a production crash.
refundforgot. The bug only fires for guests who refund, which is exactly the sort of path that unit tests skip. - The meaning of "missing" is spread thin. "A guest gets zero discount" is encoded as
: 0inside an expression inpay. If marketing later says guests get 1% off, somebody has to find every place that defaulted to zero. - The type lies.
LoyaltyAccount accountin Java says "an account". The compiler cannot tell you it might be null. Python's type checker can (with| None), but then you need the checks anyway.
Structure
classDiagram
class Checkout {
-directory: LoyaltyDirectory
-log: AuditLog
+pay(customerId, subtotal) long
+refund(customerId, amount) long
}
class LoyaltyAccount {
<<interface>>
+discountCents(subtotal) long
+addPoints(points) void
+points() long
}
class MemberAccount {
-points: long
+discountCents(subtotal) long
+addPoints(points) void
+points() long
}
class NoLoyaltyAccount {
<<singleton>>
+discountCents(subtotal) long
+addPoints(points) void
+points() long
}
class AuditLog {
<<interface>>
+record(event) void
}
class ListAuditLog {
+record(event) void
}
class NullAuditLog {
<<singleton>>
+record(event) void
}
class LoyaltyDirectory {
+find(customerId) LoyaltyAccount
}
Checkout --> LoyaltyDirectory
Checkout --> AuditLog
LoyaltyDirectory ..> LoyaltyAccount : "returns, never null"
LoyaltyAccount <|.. MemberAccount
LoyaltyAccount <|.. NoLoyaltyAccount
AuditLog <|.. ListAuditLog
AuditLog <|.. NullAuditLog
There are two null objects here, and they show the two common flavours:
NoLoyaltyAccountis a domain null object. It represents a real business situation (a guest) and its behaviour (no discount, no points) is a business rule.NullAuditLogis an infrastructure null object. It represents an optional technical service that was not configured, and its behaviour (drop the message) is a deployment choice.
Participants
| Participant | Role in the example | Responsibility |
|---|---|---|
| Abstraction | LoyaltyAccount, AuditLog | The interface clients depend on. It must be small enough that a sensible "do nothing" exists for every method. |
| Real implementation | MemberAccount, ListAuditLog | Does the actual work. |
| Null Object | NoLoyaltyAccount, NullAuditLog | Implements every method with the neutral behaviour. Usually stateless, so one shared instance is enough. |
| Client | Checkout | Calls the abstraction without checking for absence. |
| Resolver | LoyaltyDirectory.find, the constructor default | The one place that decides to hand out the null object instead of a real one. It turns "not found" into "the guest account". |
The resolver is the participant people forget. A null object only removes null checks if something upstream guarantees that clients never see a raw null. That something is usually a lookup method (find returns the null object on a miss), a factory, or a constructor that substitutes the null object for a missing argument.
Implementation
The same checkout, rebuilt around null objects. Every client branch is gone, and the guest refund that used to crash now does the right thing.
import java.util.*;
interface AuditLog {
void record(String event);
}
final class ListAuditLog implements AuditLog {
final List<String> events = new ArrayList<>();
public void record(String event) { events.add(event); }
}
enum NullAuditLog implements AuditLog {
INSTANCE;
public void record(String event) { /* deliberately empty: auditing is off */ }
}
interface LoyaltyAccount {
long discountCents(long subtotalCents);
void addPoints(long points);
long points();
}
final class MemberAccount implements LoyaltyAccount {
private long points;
MemberAccount(long points) { this.points = points; }
public long discountCents(long subtotalCents) { return subtotalCents * 5 / 100; }
public void addPoints(long p) { points = Math.max(0, points + p); }
public long points() { return points; }
}
/** A guest: no discount, earns nothing, owes nothing. */
enum NoLoyaltyAccount implements LoyaltyAccount {
INSTANCE;
public long discountCents(long subtotalCents) { return 0; }
public void addPoints(long points) { }
public long points() { return 0; }
}
final class LoyaltyDirectory {
private final Map<String, LoyaltyAccount> byCustomer = new HashMap<>();
void enroll(String customerId, LoyaltyAccount account) {
byCustomer.put(customerId, Objects.requireNonNull(account));
}
/** Never returns null. */
LoyaltyAccount find(String customerId) {
return byCustomer.getOrDefault(customerId, NoLoyaltyAccount.INSTANCE);
}
}
final class Checkout {
private final LoyaltyDirectory directory;
private final AuditLog log;
Checkout(LoyaltyDirectory directory, AuditLog log) {
this.directory = Objects.requireNonNull(directory);
this.log = log == null ? NullAuditLog.INSTANCE : log; // the resolver for the optional log
}
Checkout(LoyaltyDirectory directory) { this(directory, NullAuditLog.INSTANCE); }
long pay(String customerId, long subtotalCents) {
LoyaltyAccount account = directory.find(customerId);
long total = subtotalCents - account.discountCents(subtotalCents);
account.addPoints(total / 100);
log.record(customerId + " paid " + total);
return total;
}
long refund(String customerId, long amountCents) {
directory.find(customerId).addPoints(-(amountCents / 100));
log.record(customerId + " refunded " + amountCents);
return amountCents;
}
}
public class NullObjectDemo {
public static void main(String[] args) {
LoyaltyDirectory directory = new LoyaltyDirectory();
MemberAccount alice = new MemberAccount(0);
directory.enroll("alice", alice);
ListAuditLog audit = new ListAuditLog();
Checkout audited = new Checkout(directory, audit);
assert audited.pay("alice", 10_000) == 9_500;
assert alice.points() == 95;
assert audited.pay("guest-7", 10_000) == 10_000;
assert audited.refund("guest-7", 10_000) == 10_000; // no crash
assert audit.events.size() == 3;
Checkout silent = new Checkout(directory); // no log configured
assert silent.refund("alice", 5_000) == 5_000;
assert alice.points() == 45;
assert directory.find("nobody") == NoLoyaltyAccount.INSTANCE;
System.out.println("ok " + audit.events);
}
}
from typing import Final, Protocol
class AuditLog(Protocol):
def record(self, event: str) -> None: ...
class ListAuditLog:
def __init__(self) -> None:
self.events: list[str] = []
def record(self, event: str) -> None:
self.events.append(event)
class _NullAuditLog:
def record(self, event: str) -> None:
pass # deliberately empty: auditing is off
def __repr__(self) -> str:
return "NULL_AUDIT_LOG"
NULL_AUDIT_LOG: Final = _NullAuditLog()
class LoyaltyAccount(Protocol):
def discount_cents(self, subtotal_cents: int) -> int: ...
def add_points(self, points: int) -> None: ...
def points(self) -> int: ...
class MemberAccount:
def __init__(self, points: int = 0) -> None:
self._points = points
def discount_cents(self, subtotal_cents: int) -> int:
return subtotal_cents * 5 // 100
def add_points(self, points: int) -> None:
self._points = max(0, self._points + points)
def points(self) -> int:
return self._points
class _NoLoyaltyAccount:
"""A guest: no discount, earns nothing, owes nothing."""
def discount_cents(self, subtotal_cents: int) -> int:
return 0
def add_points(self, points: int) -> None:
pass
def points(self) -> int:
return 0
NO_LOYALTY_ACCOUNT: Final = _NoLoyaltyAccount()
class LoyaltyDirectory:
def __init__(self) -> None:
self._by_customer: dict[str, LoyaltyAccount] = {}
def enroll(self, customer_id: str, account: LoyaltyAccount) -> None:
self._by_customer[customer_id] = account
def find(self, customer_id: str) -> LoyaltyAccount:
"""Never returns None."""
return self._by_customer.get(customer_id, NO_LOYALTY_ACCOUNT)
class Checkout:
def __init__(self, directory: LoyaltyDirectory, log: AuditLog = NULL_AUDIT_LOG) -> None:
self._directory = directory
self._log = log
def pay(self, customer_id: str, subtotal_cents: int) -> int:
account = self._directory.find(customer_id)
total = subtotal_cents - account.discount_cents(subtotal_cents)
account.add_points(total // 100)
self._log.record(f"{customer_id} paid {total}")
return total
def refund(self, customer_id: str, amount_cents: int) -> int:
self._directory.find(customer_id).add_points(-(amount_cents // 100))
self._log.record(f"{customer_id} refunded {amount_cents}")
return amount_cents
if __name__ == "__main__":
directory = LoyaltyDirectory()
alice = MemberAccount()
directory.enroll("alice", alice)
audit = ListAuditLog()
audited = Checkout(directory, audit)
assert audited.pay("alice", 10_000) == 9_500
assert alice.points() == 95
assert audited.pay("guest-7", 10_000) == 10_000
assert audited.refund("guest-7", 10_000) == 10_000 # no crash
assert len(audit.events) == 3
silent = Checkout(directory) # no log configured
assert silent.refund("alice", 5_000) == 5_000
assert alice.points() == 45
assert directory.find("nobody") is NO_LOYALTY_ACCOUNT
print("ok", audit.events)
interface AuditLog {
record(event: string): void;
}
class ListAuditLog implements AuditLog {
readonly events: string[] = [];
record(event: string): void {
this.events.push(event);
}
}
const NULL_AUDIT_LOG: AuditLog = Object.freeze({
record(_event: string): void {
/* deliberately empty: auditing is off */
},
});
interface LoyaltyAccount {
discountCents(subtotalCents: number): number;
addPoints(points: number): void;
points(): number;
}
class MemberAccount implements LoyaltyAccount {
constructor(private balance = 0) {}
discountCents(subtotalCents: number): number {
return Math.floor((subtotalCents * 5) / 100);
}
addPoints(points: number): void {
this.balance = Math.max(0, this.balance + points);
}
points(): number {
return this.balance;
}
}
/** A guest: no discount, earns nothing, owes nothing. */
const NO_LOYALTY_ACCOUNT: LoyaltyAccount = Object.freeze({
discountCents: () => 0,
addPoints: (_points: number) => {},
points: () => 0,
});
class LoyaltyDirectory {
private readonly byCustomer = new Map<string, LoyaltyAccount>();
enroll(customerId: string, account: LoyaltyAccount): void {
this.byCustomer.set(customerId, account);
}
/** Never returns undefined. */
find(customerId: string): LoyaltyAccount {
return this.byCustomer.get(customerId) ?? NO_LOYALTY_ACCOUNT;
}
}
class Checkout {
constructor(
private readonly directory: LoyaltyDirectory,
private readonly log: AuditLog = NULL_AUDIT_LOG,
) {}
pay(customerId: string, subtotalCents: number): number {
const account = this.directory.find(customerId);
const total = subtotalCents - account.discountCents(subtotalCents);
account.addPoints(Math.floor(total / 100));
this.log.record(`${customerId} paid ${total}`);
return total;
}
refund(customerId: string, amountCents: number): number {
this.directory.find(customerId).addPoints(-Math.floor(amountCents / 100));
this.log.record(`${customerId} refunded ${amountCents}`);
return amountCents;
}
}
const directory = new LoyaltyDirectory();
const alice = new MemberAccount();
directory.enroll("alice", alice);
const audit = new ListAuditLog();
const audited = new Checkout(directory, audit);
if (audited.pay("alice", 10_000) !== 9_500) throw new Error("member pay");
if (alice.points() !== 95) throw new Error("points");
if (audited.pay("guest-7", 10_000) !== 10_000) throw new Error("guest pay");
if (audited.refund("guest-7", 10_000) !== 10_000) throw new Error("guest refund"); // no crash
if (audit.events.length !== 3) throw new Error("audit");
const silent = new Checkout(directory); // no log configured
silent.refund("alice", 5_000);
if (alice.points() !== 45) throw new Error("refund points");
if (directory.find("nobody") !== NO_LOYALTY_ACCOUNT) throw new Error("identity");
console.log("ok", audit.events);
A few implementation choices are worth calling out, because interviewers ask about them.
One shared instance. Both null objects are stateless, so a single instance serves everyone. Java's enum with one constant is the tidiest way to get a serialisation-safe singleton; Python uses a module-level constant; TypeScript uses a frozen object literal. A shared instance also lets you test identity (find("nobody") == NoLoyaltyAccount.INSTANCE), which is handy in tests and debugging. This is one of the few places where a singleton is uncontroversial: there is no state to share, so none of the usual singleton problems apply.
The resolver sits at the boundary. LoyaltyDirectory.find converts a map miss into the guest account. Checkout's constructor converts a missing log into the null log. Everything inside Checkout is null-free.
Required collaborators still fail fast. The directory is not optional, so the Java constructor calls Objects.requireNonNull(directory). Only collaborators whose absence is a legitimate state get a null object. That distinction is the whole game, and the section on hidden bugs comes back to it.
Inherited behaviour stays honest. MemberAccount.addPoints clamps at zero, so a refund can't drive a balance negative. NoLoyaltyAccount.addPoints ignores the call entirely. Both satisfy the same contract: "after addPoints, points() is never negative". If the contract said "points() increases by exactly p", the null object would break it, and you would need a different design.
Null Object vs Optional, None and undefined
Modern languages give you ways to express absence in the type system: Java's Optional<T>, Python's T | None with a type checker, TypeScript's T | undefined under strictNullChecks, Kotlin's T?, Rust's Option<T>. People sometimes present these as replacements for Null Object. They are not. They answer a different question.
| Optional / nullable type | Null Object | |
|---|---|---|
| What it says | "This might be missing. Caller, you decide what that means." | "Missing has a meaning, and here it is." |
| Who handles absence | Each caller, at each use | The null class, once |
| Compiler help | Forces callers to handle absence (when the type system is strict) | Nothing to handle |
| Best when | Different callers want different behaviour for "missing", or "missing" is an error the caller must report | Every caller wants the same neutral behaviour |
| Risk | Boilerplate, .get() without a check | Silently doing nothing when something should have happened |
A good rule of thumb: use an Optional at the edge where absence is discovered, and a Null Object where absence is consumed. The repository's findById returns an Optional because "no such customer" might be a 404 for one caller and a sign-up prompt for another. Inside the checkout, where every path wants "guest behaviour", you collapse that Optional into a null object once and stop thinking about it.
import java.util.Optional;
public class OptionalBoundary {
interface Account { long discount(long subtotal); }
record Member(long rate) implements Account { public long discount(long s) { return s * rate / 100; } }
enum Guest implements Account { INSTANCE; public long discount(long s) { return 0; } }
// The repository reports absence honestly...
static Optional<Account> findById(String id) {
return id.equals("alice") ? Optional.of(new Member(5)) : Optional.empty();
}
public static void main(String[] args) {
// ...and the checkout collapses it once, at the boundary.
Account a = findById("alice").orElse(Guest.INSTANCE);
Account g = findById("guest").orElse(Guest.INSTANCE);
assert a.discount(1000) == 50;
assert g.discount(1000) == 0;
// A caller with a different need keeps the Optional and reacts differently.
boolean showSignUp = findById("guest").isEmpty();
assert showSignUp;
System.out.println("ok");
}
}
from typing import Protocol
class Account(Protocol):
def discount(self, subtotal: int) -> int: ...
class Member:
def __init__(self, rate: int) -> None:
self.rate = rate
def discount(self, subtotal: int) -> int:
return subtotal * self.rate // 100
class _Guest:
def discount(self, subtotal: int) -> int:
return 0
GUEST = _Guest()
def find_by_id(customer_id: str) -> Account | None: # honest about absence
return Member(5) if customer_id == "alice" else None
account = find_by_id("alice") or GUEST # collapse once
guest = find_by_id("bob") or GUEST
assert account.discount(1000) == 50
assert guest.discount(1000) == 0
assert find_by_id("bob") is None # another caller can still ask
print("ok")
interface Account {
discount(subtotal: number): number;
}
const member = (rate: number): Account => ({ discount: (s) => Math.floor((s * rate) / 100) });
const GUEST: Account = Object.freeze({ discount: () => 0 });
function findById(id: string): Account | undefined {
return id === "alice" ? member(5) : undefined; // honest about absence
}
const a = findById("alice") ?? GUEST; // collapse once
const g = findById("bob") ?? GUEST;
if (a.discount(1000) !== 50 || g.discount(1000) !== 0) throw new Error("discount");
// Optional chaining is a call-site null object: fine for one call, noisy for twenty.
const configuredLog = (): { record(e: string): void } | undefined => undefined;
configuredLog()?.record("ignored");
console.log("ok");
Two warnings about the Python version. First, x or GUEST treats every falsy value as missing, so if your real objects can be falsy (an account with __len__ returning 0, say), use GUEST if x is None else x. Second, Python has no compiler forcing you to handle None; the guarantee only exists if you run a type checker such as mypy or pyright.
The TypeScript snippet also shows optional chaining (log?.record(...)). It is effectively an inline null object for a single call, and it is the right tool when a value is optional in one or two places. When the same optional collaborator is used in many methods, a real null object reads better than ?. scattered everywhere, and it lets you give the no-op behaviour a name.
No-op loggers and other infrastructure null objects
Logging is the classic home of this pattern. A library should not decide where its log lines go; the application that uses the library decides. Until the application configures something, the library still needs a logger to call, and that logger should do nothing.
Python's standard library builds this in: logging.NullHandler is a handler whose emit does nothing, and the logging documentation recommends that libraries attach one to their top-level logger so that, if the application configures nothing, the library stays silent instead of triggering logging's last-resort output. SLF4J in Java does the same thing at a different level: when no logging backend is on the classpath it falls back to a no-operation logger and prints a one-time warning about it.
Two practical points apply to any no-op logger you write:
- The arguments are still evaluated.
log.debug("state=" + expensiveDump())builds the string even ifdebugdoes nothing. Real logging APIs offer lazy forms for exactly this reason (format strings with placeholders, orSupplier<String>arguments injava.util.loggingandSystem.Logger). A null logger removes the output, not the work in front of the call. - Silence is a configuration choice, so make it visible. SLF4J's one-time warning is a good model: a null object that is chosen by default rather than on purpose should say so once at startup.
The same idea runs through I/O. Java 11 added OutputStream.nullOutputStream(), Writer.nullWriter(), InputStream.nullInputStream() and Reader.nullReader(): streams that discard writes or are always at end-of-file. Go has io.Discard. Unix has /dev/null, exposed to Python as os.devnull. All of them let code that "must write somewhere" run in a context where the output does not matter, without an if (out != null) in the writing code.
Default strategies
A null object is often just the "identity" member of a family of strategies. Pricing has NoDiscount. Retry policies have NoRetry. Caches have a pass-through NoCache. Authorisation has AllowAll for local development (and, the section below argues, should never reach production by accident). Functional code has the same idea in smaller form: Function.identity() in Java, a () => {} callback in TypeScript, contextlib.nullcontext() in Python (added in 3.7) when a with block needs a context manager that does nothing.
type DiscountPolicy = (subtotalCents: number) => number;
const NO_DISCOUNT: DiscountPolicy = () => 0;
const percentOff = (pct: number): DiscountPolicy => (s) => Math.floor((s * pct) / 100);
const capped = (inner: DiscountPolicy, maxCents: number): DiscountPolicy => (s) =>
Math.min(inner(s), maxCents);
class PriceCalculator {
constructor(private readonly discount: DiscountPolicy = NO_DISCOUNT) {}
total(subtotalCents: number): number {
return subtotalCents - this.discount(subtotalCents);
}
}
if (new PriceCalculator().total(10_000) !== 10_000) throw new Error("default");
if (new PriceCalculator(percentOff(10)).total(10_000) !== 9_000) throw new Error("pct");
if (new PriceCalculator(capped(percentOff(50), 1_000)).total(10_000) !== 9_000) throw new Error("cap");
console.log("ok");
The null strategy earns its place in three ways. It is the natural constructor default, so most callers never pass anything. It is a clean base case for composition: a list of discount policies summed together starts from NO_DISCOUNT, just as a sum starts from zero. And it gives tests an obvious "nothing happens here" collaborator, which is the classic dummy test double.
When a Null Object hides a bug
This is the part of the pattern that interviewers who know it will probe. A null object turns "something is missing" into "nothing happens". That is exactly right when nothing should happen, and disastrous when something should.
A do-nothing payment gateway
Picture a PaymentGateway interface with a NullPaymentGateway whose charge returns success without contacting anyone, written so that local development works without card credentials. A configuration typo in production means the real gateway is never wired in, the resolver falls back to the null one, and every order is marked paid while no money moves. No exception, no failed request, no alert. The bug is found by finance, weeks later.
The question to ask of every null object is: "If this collaborator is missing in production, is doing nothing a correct business outcome?"
| Collaborator | Doing nothing when missing is... | Null Object? |
|---|---|---|
| Debug logger, metrics sink in a library | Correct. The application didn't ask for output. | Yes |
| Loyalty account for a guest | Correct. Guests earn nothing. | Yes |
| Optional discount, optional tracing hook | Correct. | Yes |
| Payment gateway, inventory reservation | Wrong. Money or stock is lost. | No: fail fast |
| Audit log in a regulated system | Wrong. Auditing is a legal requirement. | No: fail fast |
| Authorisation check | Wrong if the null one allows everything. | Only a deny-all one, if any |
When a collaborator is required, the honest response to its absence is to refuse to start. When it is optional but you want to know it's missing, a null object can still be the right shape, as long as it is observable:
interface PaymentGateway {
charge(orderId: string, cents: number): "charged";
}
/** Not a null object: it refuses loudly, so a wiring mistake can't pass as success. */
class UnconfiguredGateway implements PaymentGateway {
charge(orderId: string): "charged" {
throw new Error(`payment gateway not configured, refusing to charge order ${orderId}`);
}
}
/** A null object that counts what it swallowed, so dashboards can show it. */
class CountingNullMetrics {
dropped = 0;
increment(_name: string): void {
this.dropped++;
}
}
function buildGateway(env: Record<string, string | undefined>): PaymentGateway {
const key = env["PAYMENT_KEY"];
if (!key) return new UnconfiguredGateway();
return { charge: () => "charged" };
}
let refused = false;
try {
buildGateway({}).charge("o-1", 500);
} catch {
refused = true;
}
if (!refused) throw new Error("must refuse");
if (buildGateway({ PAYMENT_KEY: "k" }).charge("o-2", 500) !== "charged") throw new Error("charge");
const metrics = new CountingNullMetrics();
metrics.increment("orders");
metrics.increment("orders");
if (metrics.dropped !== 2) throw new Error("count");
console.log("ok");
Some other ways null objects go wrong:
- Query methods with no neutral answer. What should
NullAccount.lastLoginDate()return? There is no honest value. If an interface has methods like this, either split it (interface segregation) so the null object only implements the part with neutral answers, or don't use a null object for it. - Mutable null collections.
Collections.emptyList()is immutable: callingaddthrowsUnsupportedOperationException. That is a deliberate choice. A shared "empty list" that silently acceptedaddwould either lose the data or, worse, leak it to every other user of the shared instance. - Comparing against the null object. If you find
if (account == NoLoyaltyAccount.INSTANCE)spreading through the code, you have reintroduced the null check with extra steps. A single check in presentation code ("show the sign-up banner to guests") is fine. Business logic that branches on it means the behaviour belongs inside the null object or the interface needs another method. - Swallowed errors that look like success. A null object should return the neutral value, not "success".
NullPaymentGateway.chargereturning"charged"is a lie. A neutral answer to "charge this card" does not exist.
Special Case: the general form
Null Object is the most common member of a larger family. Fowler's Special Case generalises it: whenever a particular value needs special handling at many call sites, model that value as a subclass with the special behaviour built in. A null object is the special case for "missing". Others you meet in practice:
UnknownCustomervsMissingCustomer. A legacy import may have rows where the customer ID is present but doesn't resolve (unknown) and rows where it was never captured (missing). They might behave differently: unknown customers get flagged for review, missing ones don't.UnlimitedQuotafor enterprise plans, whoseremaining()returns a very large number and whoseconsume()does nothing, so rate-limiting code never needsif (plan.isEnterprise()).EmptyCart, whose checkout button is disabled and whose total is zero, though for a cart an ordinary empty list usually does the job without a special class.
The test for whether a special case deserves its own class is the same as for a null object: does the same if appear in three or more places? If yes, the special value has behaviour, and behaviour belongs on an object.
Testing with null objects
Null objects double as test doubles. When a test is about pricing, the audit log and the notifier are noise; passing NullAuditLog.INSTANCE says "this collaborator is irrelevant here" more clearly than a mock with no expectations. Gerard Meszaros's test-double vocabulary calls this a dummy: an object passed only to fill a parameter.
Two cautions. Do not let a production null object become a test assertion target; if a test needs to check that something was logged, use a recording fake such as ListAuditLog, not the null one. And test the null object's own contract explicitly (zero discount, no points change, no exception), because it is real production code that runs for every guest.
Real-world uses
These are uses you can cite in an interview with confidence:
- Java collections.
Collections.emptyList(),emptySet(),emptyMap()andemptyIterator()return shared, immutable empty instances, so methods can return "no results" without returningnull.List.of()with no arguments does the same. - Java I/O (since Java 11).
OutputStream.nullOutputStream(),Writer.nullWriter(),InputStream.nullInputStream()andReader.nullReader(). - Python logging.
logging.NullHandler, recommended in the logging documentation for library authors. - Python
contextlib.nullcontext(3.7+): a context manager that does nothing, for code that optionally wraps a block. os.devnulland/dev/null: the operating system's null sink, the original null object.- Go
io.Discard: anio.Writeron which every write succeeds and nothing is kept. - SLF4J's no-op fallback: with no logging binding present, SLF4J uses a no-operation logger and warns once.
Optional types (Optional.empty(), Kotlin's null with ?., Rust's None) are related but are not null objects. They represent absence and make the caller handle it; they do not supply behaviour.
When NOT to use it
- The collaborator is required. Payment, persistence, authorisation, legally mandated auditing. Absence is a misconfiguration and should crash at startup, not degrade silently.
- Different callers want different responses to absence. If the web layer wants a 404, the batch job wants to skip the row and the admin screen wants a "create" button, return an
Optional(or a nullable type) and let each caller decide. A single null object would be wrong for two of the three. - There is no neutral behaviour. If you can't write the null class without inventing values (
lastLoginDate()returning the epoch), the pattern doesn't fit. - The check appears once. One
if (x == null)in one method is clearer than a new class. The pattern pays when the same check repeats. - The interface is huge. A null object for a 30-method interface is 30 empty methods that drift as the interface grows. Split the interface first.
- The value is data, not a collaborator. A missing middle name is an empty string or
null, not aNullMiddleNameclass. Null objects are for things you call methods on.
The cost side is modest but real: one more class per abstraction, a little indirection when debugging ("why didn't this log?"), and the risk that absence becomes invisible. Visibility is the cost to manage.
Related patterns
- Strategy. A null object is often the "do nothing" strategy (
NoDiscount,NoRetry). Strategy is about choosing among behaviours; Null Object is the specific choice of "none", made the default. - Singleton. Stateless null objects are naturally shared single instances. This is a benign use of the singleton idea because there is no mutable global state.
- State. An idle or terminal state whose event handlers ignore everything is a null object inside a state machine, for example a vending machine's
OutOfServicestate that rejects all input. - Proxy and Decorator. A disabled feature flag is sometimes modelled as a decorator that skips the wrapped call. The difference is that a null object has nothing inside it; a decorator always wraps a real object.
- Iterator and Composite. An empty iterator is a null object for traversal, and a composite's leaves often return an empty child list instead of
null. - Factory Method. The resolver that decides between a real object and the null one is usually a factory method or a repository lookup.
- Specification. An "always true" specification is the null object of a rule set, the neutral starting point for
and-composition, just as an "always false" one is foror.
The smell that suggests it
- The same null check (
if (x != null),if x is not None,x?.) on the same collaborator appears in three or more methods. - A ternary that supplies a default, like
account != null ? account.discount(s) : 0, repeated with the same default in different places. - Logging or metrics calls wrapped in
if (logger != null)because the logger is optional. - A method that returns
nullto mean "empty", like aListor a map, forcing every caller to check before looping. - A crash report where the stack trace ends in a rarely used path (refunds, cancellations, admin actions) because that path forgot the check the main path had.
And the counter-smell, which tells you to remove a null object: incidents where something should have happened and silently didn't, traced back to a null object chosen by default.
Interview questions
-
"What's the difference between a Null Object and returning
Optional?" AnOptionalmakes absence visible and pushes the decision to each caller. A null object makes the decision once and hides absence from callers. UseOptionalwhere absence is discovered and callers may react differently, and a null object where every caller wants the same neutral behaviour. -
"Where would you use a Null Object in a parking lot or checkout design?" For optional collaborators: a no-op notifier when the customer has no phone number, a
NoDiscountpricing rule as the default, a guest loyalty account. Not for the payment processor or the spot allocator, which are required. -
"Isn't a Null Object just hiding bugs?" It can. The safeguard is the question "is doing nothing a correct outcome if this is missing in production?" If yes, a null object. If no, fail fast at startup. For optional-but-important collaborators, make the null object observable: warn once, or count what it swallowed.
-
"Should a Null Object be a singleton?" If it is stateless, yes, because there is nothing to separate between instances and sharing avoids allocation. In Java an enum constant is the cleanest form. If it carries state (rare), it shouldn't be shared.
-
"What should a null object return from a query method?" The value that makes the surrounding computation correct for the absent case: zero for amounts, empty collections,
falsefor permissions. If no such value exists, the interface should be split or the pattern isn't appropriate. -
"How is Null Object related to Liskov substitution?" It must be a full substitute: anything a client may assume about the interface must hold for the null implementation. If the contract says "
addPoints(p)increasespoints()byp", a null object that ignores the call breaks LSP. The fix is to write the contract so that the neutral behaviour is allowed, or not to use the pattern. -
"What is the Special Case pattern?" The generalisation: any value that needs the same special handling in many places becomes its own subclass carrying that behaviour. Null Object is the special case for "missing". Others include unknown customers or unlimited quotas.
-
"How do you test code that uses null objects?" Test the null object's contract directly (neutral returns, no exceptions). In other tests, use null objects as dummies for irrelevant collaborators, and use recording fakes, not null objects, when the test needs to verify an interaction.
-
"Your null logger is making the app slow. How?" The arguments are evaluated before the no-op call: string concatenation,
toString()on big objects, serialisation. Use lazy logging APIs (placeholders or suppliers), or check the level once for genuinely expensive messages.
Further reading
- Behavioral patterns overview, the grouped page this course links down from
- Liskov substitution principle, the contract a null object must honour
- Common LLD mistakes, especially over-patterning and missing edge cases
- Pattern selection guide, for choosing between Null Object, Strategy and a plain
Optional