Pattern 8Replacing Null Object

Intent

To avoid scattering null checks throughout our code by encapsulating the action taken for null references into a surrogate null object

Overview

A common way to represent the lack of a value in Java is to use a null reference. This leads to a lot of code that looks like so:

 
if​(null == someObject){
 
// default null handling behavior
 
}​else​{
 
someObject.someMethod()
 
}

This style leads to scattering null handling logic throughout our code, often repeating it. If we forget to check for null it may lead to a program crashing NullPointerException, even if there is a reasonable default behavior that can handle the lack of a value.

A common solution to this is to create a singleton null object that ...

Get Functional Programming Patterns in Scala and Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.