Browser docs

Null Object

Intent

In most object-oriented languages, such as Java or C#, references may be null. These references need to be checked to ensure they are not null before invoking any methods, because methods typically cannot be invoked on null references. Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach over a working default implementation is that a Null Object is very predictable and has no side effects: it does nothing.

Explanation

Real world example

We are building a binary tree from nodes. There are ordinary nodes and “empty” nodes. Traversing the tree normally should not cause errors, so we use null object pattern where necessary.

In plain words

Null Object pattern handles “empty” objects gracefully.

Wikipedia says

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral (“null”) behavior. The null object design pattern describes the uses of such objects and their behavior (or lack thereof).

Programmatic Example

Here’s the definition of Node interface.

 1public interface Node {
 2
 3  String getName();
 4
 5  int getTreeSize();
 6
 7  Node getLeft();
 8
 9  Node getRight();
10
11  void walk();
12}

We have two implementations of Node. The normal implementation NodeImpl and NullNode for empty nodes.

 1@Slf4j
 2public class NodeImpl implements Node {
 3
 4  private final String name;
 5  private final Node left;
 6  private final Node right;
 7
 8  /**
 9   * Constructor.
10   */
11  public NodeImpl(String name, Node left, Node right) {
12    this.name = name;
13    this.left = left;
14    this.right = right;
15  }
16
17  @Override
18  public int getTreeSize() {
19    return 1 + left.getTreeSize() + right.getTreeSize();
20  }
21
22  @Override
23  public Node getLeft() {
24    return left;
25  }
26
27  @Override
28  public Node getRight() {
29    return right;
30  }
31
32  @Override
33  public String getName() {
34    return name;
35  }
36
37  @Override
38  public void walk() {
39    LOGGER.info(name);
40    if (left.getTreeSize() > 0) {
41      left.walk();
42    }
43    if (right.getTreeSize() > 0) {
44      right.walk();
45    }
46  }
47}
48
49public final class NullNode implements Node {
50
51  private static final NullNode instance = new NullNode();
52
53  private NullNode() {
54  }
55
56  public static NullNode getInstance() {
57    return instance;
58  }
59
60  @Override
61  public int getTreeSize() {
62    return 0;
63  }
64
65  @Override
66  public Node getLeft() {
67    return null;
68  }
69
70  @Override
71  public Node getRight() {
72    return null;
73  }
74
75  @Override
76  public String getName() {
77    return null;
78  }
79
80  @Override
81  public void walk() {
82    // Do nothing
83  }
84}

Then we can construct and traverse the binary tree without errors as follows.

 1    var root = new NodeImpl("1",
 2            new NodeImpl("11",
 3                new NodeImpl("111", NullNode.getInstance(), NullNode.getInstance()),
 4                NullNode.getInstance()
 5            ),
 6            new NodeImpl("12",
 7                NullNode.getInstance(),
 8                new NodeImpl("122", NullNode.getInstance(), NullNode.getInstance())
 9            )
10        );
11    root.walk();

Program output:

1
11
111
12
122

Class diagram

alt text

Applicability

Use the Null Object pattern when

  • You want to avoid explicit null checks and keep the algorithm elegant and easy to read.

Credits