Null Object replaces null as the meaning of "nothing here" with a real object that implements the expected interface and does nothing, or returns a neutral value. Callers stop asking if (logger != null) before every use: they always get something they can call. The pattern is not in the Gang of Four book (Bobby Woolf described it in Pattern Languages of Program Design 3), but you use it every time you write to /dev/null or get back an empty list instead of null.
Think of it like
A stand-in with nothing to say
A theater keeps an understudy for every role, so the show never stops to ask whether the actor turned up. Picture a non-speaking part: a guard who stands by the door. If that actor is out, a stand-in in the costume takes the spot, and the other actors deliver their lines to him exactly as written. Nobody on stage checks who is under the helmet, and nothing in the play changes. The stand-in is the null object: same costume (interface), same cues, no lines of his own.
The problem
An OrderService can log what it does, but a logger is optional: a command-line tool or a test may not configure one. Orders can also carry a discount, but a guest has no coupon. The usual way to say "there is none" is null, and null has no methods, so every use has to be guarded. This is the Before version in the visualizer above, with the Log refunds change applied.
class OrderService {
constructor(private log: Logger | null = null) {}
checkout(total: number, d: Discount | null) {
let due = total;
if (d) due = d.apply(total);
if (this.log) this.log.info(`paid ${due}`);
return due;
}
refund(amt: number) {
this.log.info(`refund ${amt}`); // forgot the check
}
}- The checks multiply. Every method that touches the logger or the discount repeats the same question. Half of
checkout()above is about absence, not about orders. - One forgotten check is a crash.
refund()was added later and nobody remembered. In Java, Python or plain JavaScript it fails at run time, on the path that happens to have no logger, which is often not the path the tests cover. - The decision is spread out. What "no logger" means (stay quiet) is decided again at every call site, and two call sites can decide differently.
- Callers inherit the burden. Anything that receives the logger or the discount from this class has to check too. Tony Hoare, who added null references to ALGOL W in 1965, later called them his "billion-dollar mistake".
The pattern
Intent: provide an object that stands in for "no object": it implements the same interface and does nothing, or returns a neutral value. Code that uses the interface no longer has to tell "something" from "nothing"; the choice is made once, where the object is created.
- Abstraction (
Logger,Discount) - The interface the client depends on. It is the same with or without the pattern; Null Object adds no new interface.
- Real object (
TenOff, a console logger) - An implementation that does real work.
- Null object (
NullLogger,NoDiscount) - An implementation whose methods do nothing (
info()has an empty body) or return the neutral value (apply(total)returnstotal). It has no state, so one instance can be shared. - Client (
OrderService) - Calls the interface without checking for absence. Somebody else, usually its constructor default, a factory or the composition root, decides whether it gets a real or a null object.
What the visualizer shows
- Before: the class diagram marks both dependencies
0..1: maybe there, maybe not. In the Objects viewsvcholdslog = null, and the code panel jumps toif (d)andif (this.log)as each check passes or skips a call. Nothing ever reaches a logger. - With Null Object:
NullLoggerandNoDiscountappear in the class diagram as ordinary implementations.svc's constructor createsnullLog, so the field holds a reference instead ofnull, and the Sequence view showsinfo("paid 180")andinfo("paid 50")arriving on thenullLoglifeline and returning without doing anything. - Log refunds (the change request): Before, the new
refund()forgets the check and the run ends with the real JavaScript errorTypeError: Cannot read properties of null (reading 'info'). With Null Object, the samerefund()sendsinfo("refund 50")tonullLogand the run completes.
Walkthrough
- 1
Default to the null object
With With Null Object selected, the client writes
new OrderService()without a logger. The constructor's default parameter createsnullLog, aNullLogger, and stores it inlog. From here onlogis nevernull. - 2
A member pays
svc.checkout(200, ten)callsten.apply(200), which returns180, then callsnullLog.info("paid 180"). The call is declared byLogger,NullLogger.inforuns, its body is empty, and control returns.checkoutreturns180. - 3
A guest pays
The guest has no coupon, so the client passes
none, aNoDiscount, instead ofnull.none.apply(50)returns50unchanged, the log line goes tonullLogagain, andcheckoutreturns50. Same code path for both customers. - 4
Compare with Before
Switch to Before. The results are the same (
180and50), butcheckout()takes a different branch for each order:if (d)passes for the member and skips for the guest, andif (this.log)skips both times. - 5
Log refunds
Apply Log refunds. With Null Object,
svc.refund(50)sendsinfo("refund 50")tonullLogand finishes. Before,refund()callsthis.log.infoonnull:svc.refundthrows, nobody catches it, and the run stops.
Before and after
Absence as null
- Every use of an optional dependency needs a check
- A missed check compiles in many languages and crashes at run time
- What "nothing" means is decided again at each call site
- No extra classes; absence is visible in the code
With Null Object
- Callers use the interface the same way, always
- Nothing to forget: new call sites cannot hit
null - "Nothing" is defined once, in the null object
- One small class per interface, kept in step with it; absence is hidden from callers
| Change request: log refunds | Before | With Null Object |
|---|---|---|
| Existing classes edited | 1 (OrderService) | 1 (OrderService) |
| New classes | 0 | 0 |
| Lines changed in existing classes | 3 (+3 −0) | 3 (+3 −0) |
| Run completes | No: TypeError in refund() | Yes |
The panel shows the same cost for both versions, and that is the honest result: Null Object does not make changes cheaper to write. The correct Before version would be one line longer (if (this.log) in front of the call); the version shown forgot that line, and the cost turned up at run time instead. With Null Object there is nothing to remember. The pattern has its own cost in the other direction: if Logger gains a method, NullLogger must implement it too (an empty body, but an edit), and so must every other implementation.
Variations
Special Case: the general idea
Martin Fowler's Special Case (in Patterns of Enterprise Application Architecture) generalizes Null Object: a subclass that provides special behavior for a particular case, not only for "nothing". A repository that finds no customer returns an UnknownCustomer whose name is "guest" and whose discount is 0; a MissingAddress prints as "no address on file". The special case does not have to do nothing: it does the right default thing, and it can offer an isUnknown() for the few callers that genuinely must react. The second implementation below is a Special Case.
Sharing one instance
A null object has no state, so every client can share one: a static NullLogger.INSTANCE, Java's Collections.emptyList() that returns the same immutable empty list every time. That is a Singleton in the harmless sense (immutable, no global mutable state), and the same reasoning as Flyweight: identical immutable objects need not be copied. Pass the shared instance through constructors like any other dependency (Dependency Injection) rather than reaching for it from inside the class.
Optional types: making absence visible instead
| Language | Type-system tool | What it forces |
|---|---|---|
| TypeScript | strictNullChecks, Logger | null, optional chaining log?.info(msg) | The compiler rejects this.log.info() until null is ruled out. The visualizer's Before refund() would not compile under strict mode |
| Kotlin | Nullable types Logger?, safe call log?.info(msg), elvis ?: | A non-null Logger can never hold null; a Logger? must be checked or safe-called |
| Java | Optional<Customer> (Java 8) as a return type | Callers must unwrap: orElse(...), map(...), ifPresent(...). Plain references can still be null |
| Rust | Option<T>: Some(value) or None | There is no null reference at all; match or combinators handle both cases |
| C++ | std::optional<T> (C++17), references for must-exist values | A reference cannot be null; an optional must be tested before use |
The trade-off is about who knows. Optional types force every caller to handle absence, which is right when absence matters to the caller (a lookup that found nothing, a value that must be entered). Null Object hides absence, which is right when every caller would handle it the same way, by doing nothing. They combine well: repo.find(id) returns Optional<Customer> where the caller must decide, and orElse(UnknownCustomer.INSTANCE) turns it into a Special Case where it need not.
In real code
| Where | The null object | What it does |
|---|---|---|
| Unix | /dev/null | Writes succeed and are discarded; reads return end of file. cmd > /dev/null silences a program without changing it |
| Java collections | Collections.emptyList(), emptyMap(), emptyIterator() | Shared immutable empty instances: iterate zero times instead of returning null (mutators throw, because adding to "nothing" is a real error) |
| Java I/O (Java 11+) | OutputStream.nullOutputStream(), Writer.nullWriter() | Streams that discard everything written to them |
| SLF4J (Java logging facade) | NOPLogger | The no-operation logger SLF4J falls back to when no logging backend is on the classpath: every call does nothing |
Python logging | logging.NullHandler | A handler that does nothing. Libraries add it to their logger so they never print unless the application configures logging |
Python contextlib | nullcontext() | A context manager that does nothing, for code that uses with only sometimes |
| Go | io.Discard | An io.Writer on which every Write succeeds without doing anything |
| .NET | NullLogger.Instance (Microsoft.Extensions.Logging), Stream.Null | A shared logger that discards messages; a stream with no backing store |
When to use it, and when not to
Reach for Null Object when
- A dependency is optional and "do nothing" is the right behavior: logging, metrics, tracing, event listeners, callbacks
- There is an obvious neutral value: zero discount, an empty list, an identity transform
- The same null check is repeated across many call sites
- You want a safe default before anything is configured, as with a default Strategy
Keep null (or Optional) when
- The caller must react to absence: "user not found" should show an error, not greet a ghost
- Doing nothing would hide a failure: payments, writes that must persist, security checks
- There is no meaningful neutral behavior for some methods (what does a null
Connectionreturn fromquery()?) - The language already forces handling (Kotlin, Rust, strict TypeScript) and the check is cheap and clear
Null Object vs similar patterns
| Pattern | Relation to Null Object | Example |
|---|---|---|
| Strategy | A null object is often the default strategy: the algorithm that changes nothing | NoDiscount as the default pricing strategy |
| State | An idle or "nothing to do" state whose event handlers ignore events is a null state | A Locked door state whose lock() does nothing |
| Proxy | A proxy controls access to a real subject; a null object has no real subject behind it | A virtual proxy loads the image; a null image draws nothing |
| Optional / Maybe types | Make absence explicit in the type so callers must handle it; Null Object hides it | Optional<Customer> vs UnknownCustomer |
| Test fakes and stubs | Also stand-ins behind an interface, but they record or script behavior for a test; a null object is production code that does nothing | FakeGateway in Dependency Injection vs NullLogger |
Implementation
The scenario as a complete program: a Logger interface with a console logger and a NullLogger, a Discount interface with PercentOff and NoDiscount, and an OrderService whose logger and discount default to shared null objects. The demo runs the service once with a console logger and once with no logger at all; refund() works in both without a null check. In C++ the service holds references, which cannot be null.
from typing import Protocol
class Logger(Protocol):
def info(self, msg: str) -> None: ...
class ConsoleLogger:
def info(self, msg: str) -> None:
print(f"[info] {msg}")
class NullLogger:
"""Does nothing, on purpose. Stateless, so share one."""
def info(self, msg: str) -> None:
pass
NULL_LOGGER = NullLogger()
class Discount(Protocol):
def apply(self, total: float) -> float: ...
class PercentOff:
def __init__(self, percent: float) -> None:
self.percent = percent
def apply(self, total: float) -> float:
return total - total * self.percent / 100
class NoDiscount:
"""The neutral discount: returns the total unchanged."""
def apply(self, total: float) -> float:
return total
NO_DISCOUNT = NoDiscount()
class OrderService:
def __init__(self, log: Logger = NULL_LOGGER) -> None:
self.log = log
def checkout(self, total: float,
d: Discount = NO_DISCOUNT) -> float:
due = d.apply(total)
self.log.info(f"paid {due}")
return due
def refund(self, amount: float) -> None:
self.log.info(f"refund {amount}") # no check needed
if __name__ == "__main__":
shop = OrderService(ConsoleLogger())
print(shop.checkout(200, PercentOff(10))) # logs, 180.0
print(shop.checkout(50)) # logs, 50
shop.refund(50)
quiet = OrderService() # no output from the service
print(quiet.checkout(200, PercentOff(10))) # 180.0
quiet.refund(50)Key takeaways
- Null Object replaces
nullwith an object that implements the same interface and does nothing or returns a neutral value, so callers never branch on absence. - The decision "real or nothing" is made once, where the object is created (a constructor default, a factory, the composition root), instead of at every call site.
- In the visualizer, the "log refunds" change costs the same 3 lines either way, but the Before version that forgot its check crashed with
Cannot read properties of null; the null object version cannot crash that way. - Neutral must be truly neutral: use it for logging, listeners and zero discounts, never where silently doing nothing hides a failure.
- Optional types force callers to handle absence; Null Object hides it. Use Optional where the caller must decide, and Special Case (
UnknownCustomer) where every caller would do the same thing. - Null objects are stateless, so share one instance (
Collections.emptyList(),NullLogger.Instance).
Common pitfalls
- A null object for something that must not fail silently: a
NullPaymentGatewaythat reports success, or aNullRepositorythat drops writes. - Returning values that are not neutral: a null discount that returns
0instead of the total, or a null customer with an empty name that breaks a greeting. Neutral depends on the operation. - Checking for the null object everywhere (
if (log instanceof NullLogger)) brings the branches back. If callers keep needing to know, absence should be explicit. - Forgetting to update the null object when the interface grows, or giving it state (counters, buffers) so the shared instance leaks data between users.
- Mixing styles: some code paths pass
nulland others pass the null object, so callers still need checks. Pick one at each boundary and enforce it (a non-null type,Objects.requireNonNull).
Interview tips
- Open with the problem: repeated
if (x != null)checks and the crash when one is missed. Then show the null object as one more implementation of the existing interface, injected by default. - Name real examples:
/dev/null,Collections.emptyList(), Python'slogging.NullHandler, Go'sio.Discard, SLF4J's NOP logger. - Be ready to compare with
Optionaland nullable types: Optional makes the caller handle absence, Null Object makes it unnecessary. Say which you would pick for a logger (null object) and forfindUser(id)(Optional or Special Case, depending on whether callers must react). - In LLD rounds, use it for optional collaborators: a
NoOpNotifierwhen notifications are off, aNoDiscountpricing rule, anEmptyCart.
Real-world applications
- Optional loggers, metrics and tracing clients in libraries (
NullHandler,NullLogger.Instance, no-op tracers). - Empty collections and iterators returned instead of
null. - Output sinks that discard data:
/dev/null,io.Discard,OutputStream.nullOutputStream(). - Default strategies and policies: no discount, no retry, no compression.
- Special cases in domain models: guest or unknown customers, missing addresses, an unassigned ticket owner.
- Default event listeners and callbacks, so components can call them without checking whether anyone subscribed.
Test yourself
In the visualizer's With Null Object version, what happens when svc.checkout(50, none) logs?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.