The Null Object pattern is a simple strategy to remove existence checks from code.
Take a look at the following php classes:
With just the name of the animal that we want to hear, we can create dynamic instances. These classes allow us to write this simple implementation:
We run into a bit of trouble however, when we want to hear from an animal whose class has not been defined.
There are a couple of solutions to this problem. Amending the animal factory class in the following way would be a slight improvement:
The result would be more helpful to the developer implementing the class:
Now the error message is less generic. Also, this approach outputs a stack trace so the problem can be tracked down more easily. Although an improvement over the unmodified AnimalFactory class, the exception still results in a fatal error which halts the program’s execution. In some cases this is undesirable.
To avoid stopping the script we can change our implementation by adding a check for the existance of the animal instance:
But what if we want to avoid adding this conditional to our code? Instead of asking if the animal instance exists can we simply expect the output of the factory class to say something even if no proper animal class has been established yet? In this situation the Null Object pattern can prove useful. A Null Object is designed to be substitable for instances of other objects but only outputs the default or base case behavior.
It’s essential that the Null Object has the same interface as the other classes:
To use it, we modify the AnimalFactory like so:
Now nothing will go wrong when we try and run the program with the unaccounted for name:
Traditionally, Null Objects are so named because they return a literal null value:
Whether or not this is needed in your program is up to you.