Difficulty

Null Object Pattern

This patterns focuses on providing a solution for invoking on null reference. In Java, we use null reference to convey absence of an object.

Instead of making sure we check for possible null values being assigned to a variable, we create an empty interface, and point to it. This empty interface defines so called null or call do-nothing behavior.

Let’s say we have a table with costumer details. We would like to pass, to another method, a list of all the customers with their address based in Slovenia. In case we have no costumers from this country, instead of returning a null value, we return an empty List.

Use this pattern only when sure it wont make bugs appear as a normal program execution. It shouldn’t be used to avoid null checks, this pattern doesn’t make our code easier to read nor being easier to write.

Note, with Java 8, we can use an Optional object instead. This class provides a type-level solution for representing optional values instead of null references.

Last update 01.08.2019.
For possible mistakes in content or typos, I apologise and kindly ask you to report here.