Patterncore
Null Object
Also called null object pattern, null object, Stub, Active Nothing.
A null object has the same interface as a real collaborator but does nothing. A client can use it in place of null, so the client needs no checks for null.
- Family
- behavioral-design
- Intent
- Provide a surrogate for another object that shares the same interface but does nothing, so that clients do not have to check for nil or some other special value.
- Also called
- Stub, Active Nothing
Intent
Null Object provides a surrogate for another object. The surrogate shares the same interface but does nothing. It encapsulates the implementation decisions of how to "do nothing" and hides those details from its collaborators.1
Problem
An object often needs a collaborator, and sometimes no real collaborator is available. A common solution is a null reference. A null reference does not implement the expected interface, so the calling code needs conditional checks.2 Fowler says that nulls "defeat polymorphism". If a variable can be null, you must surround it with null test code, and often you write similar code in many places.3
Here a checkout takes an optional logger. pay checks for None, but refund does not:
This code runs but gives a wrong answer on purpose.
class ConsoleLogger:
def log(self, message):
print(f"log: {message}")
class Checkout:
def __init__(self, logger=None):
self.logger = logger
def pay(self, amount):
if self.logger is not None:
self.logger.log(f"paid {amount}")
return f"receipt: {amount}"
def refund(self, amount):
self.logger.log(f"refunded {amount}") # the check is missing
return f"refund: {amount}"
checkout = Checkout()
print(checkout.pay(10))
try:
print(checkout.refund(10))
except AttributeError as error:
print(f"error: {error}")
receipt: 10
error: 'NoneType' object has no attribute 'log'
Solution
Make a class that implements the interface of the collaborator and does nothing in each method. Give a client an instance of this class instead of null.1
Client ----> AbstractObject
request()
^
__________|__________
| |
RealObject NullObject
request(): request():
real behaviour do nothing
The participants work as follows:1
- Client requires a collaborator.
- AbstractObject declares the interface for the collaborator of the client.
- RealObject is a concrete subclass whose instances provide the useful behaviour that the client expects.
- NullObject provides an interface identical to that of AbstractObject, so that a null object can be substituted for a real object. It implements the interface to do nothing. Some requests can give a null result.
What it means to do nothing is subjective. It depends on the behaviour that the client expects. When there is more than one way to do nothing, more than one NullObject class can be necessary.1
Example
The example files show one program in each language. A Checkout takes a logger with one method, log. ConsoleLogger prints each message, and NullLogger does nothing. The checkout calls its logger with no check. The program pays 10 with a console logger and 20 with a null logger, and prints:
log: paid 10
receipt: 10
receipt: 20
class ConsoleLogger:
def log(self, message):
print(f"log: {message}")
class NullLogger:
def log(self, message):
pass # do nothing
class Checkout:
def __init__(self, logger):
self.logger = logger
def pay(self, amount):
self.logger.log(f"paid {amount}") # no check for None
return f"receipt: {amount}"
print(Checkout(ConsoleLogger()).pay(10))
print(Checkout(NullLogger()).pay(20))
log: paid 10
receipt: 10
receipt: 20
- Verdict: idiom. Python has duck typing, so
NullLoggerneeds only alogmethod that does nothing. The standard library has null objects of this kind, for examplecontextlib.nullcontextandlogging.NullHandler.
#include <iostream>
#include <string>
struct Logger {
virtual ~Logger() = default;
virtual void log(const std::string& message) = 0;
};
struct ConsoleLogger : Logger {
void log(const std::string& message) override {
std::cout << "log: " << message << "\n";
}
};
struct NullLogger : Logger {
void log(const std::string&) override {} // do nothing
};
class Checkout {
public:
explicit Checkout(Logger& logger) : logger_(logger) {}
std::string pay(int amount) {
logger_.log("paid " + std::to_string(amount));
return "receipt: " + std::to_string(amount);
}
private:
Logger& logger_;
};
int main() {
ConsoleLogger console;
NullLogger silent;
std::cout << Checkout(console).pay(10) << "\n";
std::cout << Checkout(silent).pay(20) << "\n";
}
log: paid 10
receipt: 10
receipt: 20
- Verdict: idiom.
NullLoggeroverrides the pure virtual function with an empty body. The checkout holds a reference to aLogger.
interface Logger {
void log(String message);
}
class ConsoleLogger implements Logger {
public void log(String message) {
System.out.println("log: " + message);
}
}
class NullLogger implements Logger {
public void log(String message) {} // do nothing
}
class Checkout {
private final Logger logger;
Checkout(Logger logger) {
this.logger = logger;
}
String pay(int amount) {
logger.log("paid " + amount); // no check for null
return "receipt: " + amount;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Checkout(new ConsoleLogger()).pay(10));
System.out.println(new Checkout(new NullLogger()).pay(20));
}
}
log: paid 10
receipt: 10
receipt: 20
- Verdict: idiom.
NullLoggerimplements theLoggerinterface with an empty method.
using System;
interface ILogger
{
void Log(string message);
}
class ConsoleLogger : ILogger
{
public void Log(string message) => Console.WriteLine($"log: {message}");
}
class NullLogger : ILogger
{
public static readonly NullLogger Instance = new NullLogger();
public void Log(string message) { } // do nothing
}
class Checkout
{
private readonly ILogger logger;
public Checkout(ILogger logger) => this.logger = logger;
public string Pay(int amount)
{
logger.Log($"paid {amount}"); // no check for null
return $"receipt: {amount}";
}
}
class Program
{
static void Main()
{
Console.WriteLine(new Checkout(new ConsoleLogger()).Pay(10));
Console.WriteLine(new Checkout(NullLogger.Instance).Pay(20));
}
}
log: paid 10
receipt: 10
receipt: 20
- Verdict: idiom.
NullLoggerimplementsILoggerwith an empty method. It has no state, so one shared instance is sufficient.
class ConsoleLogger {
log(message) {
console.log(`log: ${message}`);
}
}
class NullLogger {
log(message) {} // do nothing
}
class Checkout {
constructor(logger) {
this.logger = logger;
}
pay(amount) {
this.logger.log(`paid ${amount}`); // no check for null
return `receipt: ${amount}`;
}
}
console.log(new Checkout(new ConsoleLogger()).pay(10));
console.log(new Checkout(new NullLogger()).pay(20));
log: paid 10
receipt: 10
receipt: 20
- Verdict: idiom. Any object with a
logmethod can be the logger, soNullLoggeris a class with an empty method.
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
log(message: string): void {
console.log(`log: ${message}`);
}
}
class NullLogger implements Logger {
log(_message: string): void {} // do nothing
}
class Checkout {
private logger: Logger;
constructor(logger: Logger) {
this.logger = logger;
}
pay(amount: number): string {
this.logger.log(`paid ${amount}`);
return `receipt: ${amount}`;
}
}
console.log(new Checkout(new ConsoleLogger()).pay(10));
console.log(new Checkout(new NullLogger()).pay(20));
log: paid 10
receipt: 10
receipt: 20
- Verdict: idiom.
NullLoggerimplements theLoggerinterface with an empty method.
package main
import "fmt"
type Logger interface {
Log(message string)
}
type ConsoleLogger struct{}
func (ConsoleLogger) Log(message string) { fmt.Println("log: " + message) }
type NullLogger struct{}
func (NullLogger) Log(string) {} // do nothing
type Checkout struct {
logger Logger
}
func (c Checkout) Pay(amount int) string {
c.logger.Log(fmt.Sprintf("paid %d", amount)) // no check for nil
return fmt.Sprintf("receipt: %d", amount)
}
func main() {
fmt.Println(Checkout{ConsoleLogger{}}.Pay(10))
fmt.Println(Checkout{NullLogger{}}.Pay(20))
}
log: paid 10
receipt: 10
receipt: 20
- Verdict: idiom.
NullLoggeris an empty struct whoseLogmethod does nothing. The standard library has the same idea inio.Discard, aWriteron which allWritecalls succeed without doing anything.
trait Logger {
fn log(&self, message: &str);
}
struct ConsoleLogger;
impl Logger for ConsoleLogger {
fn log(&self, message: &str) {
println!("log: {message}");
}
}
struct NullLogger;
impl Logger for NullLogger {
fn log(&self, _message: &str) {} // do nothing
}
struct Checkout<'a> {
logger: &'a dyn Logger,
}
impl Checkout<'_> {
fn pay(&self, amount: u32) -> String {
self.logger.log(&format!("paid {amount}"));
format!("receipt: {amount}")
}
}
fn main() {
println!("{}", Checkout { logger: &ConsoleLogger }.pay(10));
println!("{}", Checkout { logger: &NullLogger }.pay(20));
}
log: paid 10
receipt: 10
receipt: 20
- Verdict: idiom.
NullLoggeris a unit struct that implements theLoggertrait with an empty method. The other choice is a field of typeOption<&dyn Logger>.
Consequences
The benefits:1
- Client code is simple. Clients treat real and null collaborators uniformly, and they do not need code that handles the null collaborator specially.
- The do-nothing code is in one place, and it is easy to find and to reuse. All clients that need a collaborator to do nothing do nothing the same way.
The costs:
- A new class for each interface. The pattern can necessitate a new NullObject class for every new AbstractObject class.1
- Disagreement. The pattern can be difficult to implement if different clients do not agree on how the null object should do nothing.1
- Hidden errors. The pattern can make errors appear as normal program execution.2
Here a lookup returns a null customer for an unknown id. The caller has a typing error in the id, but the program prints a bill and no error:
class Customer:
def __init__(self, name, balance):
self.name = name
self.balance = balance
class NullCustomer:
name = "occupant"
balance = 0
customers = {"c-1": Customer("Ada", 30)}
def find_customer(customer_id):
return customers.get(customer_id, NullCustomer())
customer = find_customer("c-l") # a typing error: "l" for "1"
print(f"bill for {customer.name}: {customer.balance}")
bill for occupant: 0
Where the difference matters to its logic, the caller can still check explicitly, for example whether a returned list is empty.2
When not to use it
- Some clients must act differently when no collaborator is present. Then the logic that is specific to null moves into the clients again, and the code can become harder to read.2
- The object must change from doing nothing to real behaviour. A null object does not transform into a real object. A single object that must change in this way should be a Proxy.1
- The do-nothing behaviour must be mixed into the real behaviour of several collaborating objects. The same do-nothing behaviour cannot easily be added to several classes, unless they all delegate to a class that can be a null object class.1
Variants and related patterns
- Singleton. A null object usually has no state, so many instances are identical. The NullObject class is often a Singleton.1
- Special instance. A special instance of RealObject with null values can be the null object, so no subclass is necessary. For example, a composite object whose list of children is empty acts like a leaf.1 In the same way, a function can return an empty list instead of null, and the caller iterates over it with no special handling.2
- Strategy and State. A null object can be a special case of Strategy, the strategy that does nothing. It can also be a special case of State, the state in which the client does nothing.12
- Proxy. A proxy controls access to a real subject. A null object does not hide a real object; it replaces the real object.1
- Special Case. The summary of Fowler's Special Case is "A subclass that provides special behavior for particular cases". Instead of null or an odd value, a function returns a special case that has the same interface as what the caller expects.3 The refactoring Introduce Special Case has the alias Introduce Null Object.4
- Option types. An option type represents an optional value in the type itself. In Rust, every
Optionis eitherSomeand contains a value, orNone.5 Java'sOptionalis a container object that can contain a non-null value or not. It is primarily for method return types where "no result" must be represented and where null is likely to cause errors.6 In contrast, clients of a null object normally do not know whether they have a real or a null collaborator.1
Known uses
- In VisualWorks Smalltalk,
NoControlleris a controller for a view that ignores all input.NullDragModedoes nothing when the user drags a visual that cannot be resized, andNullScopeis the outer scope of the global scope.1 - Python's
contextlib.nullcontextis a context manager that does no additional processing. It is a stand-in for an optional context manager.78 - Python's
logging.NullHandleris a handler that does nothing. A library adds it to its top-level logger, so a user who does not configure logging gets no warning.9 - Go's
io.Discardis aWriteron which allWritecalls succeed without doing anything.10
References
- Bobby Woolf, The Null Object Pattern, Knowledge Systems Corp., draft of 07/28/96, Intent; Also Known As; Motivation; Applicability; Participants; Consequences; Implementation 1, 2, 4, 5, 6, 7; Known Uses; Related Patterns
- Null object pattern, Wikipedia, Introduction; Description; Relation to other patterns; Criticism
- Martin Fowler, Special Case, Catalog of Patterns of Enterprise Application Architecture, Special Case
- Martin Fowler, Introduce Special Case, Catalog of Refactorings, Introduce Special Case, aliases
- The Rust Standard Library, Module std::option, Module documentation, first paragraph
- Java SE 25 API, Class Optional, Class description
- The Python Standard Library, contextlib, Utilities for with-statement contexts, contextlib.nullcontext
- CPython v3.14.0 source, Lib/contextlib.py, class nullcontext, lines 775 to 799
- CPython v3.14.0 source, Lib/logging/__init__.py, class NullHandler, lines 2265 to 2282
- Go go1.25.0 source, src/io/io.go, Discard, lines 637 to 649
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag WKQWQK Edit this page History Report an error Markdown