Null Object
Null Object is a behavioural design pattern based on inheritance which creates a valid representation of null
objects in a system, in order to avoid returning null
objects, on which respective null checks would be needed to prevent NullPointerException
and unexpected behaviour of the application objects.
Introduction
It’s common to write methods that return null
in situations where the requested information is not present or some conditions are not met in order to execute some chunk of code. However, sometimes this behaviour is poorly documented so it takes the developers using a given API by surprise, moreover, it can force that said developers to write lots of null checks to avoid runtime exceptions.
On either way, the application code might end up with a lack of cohesion and not clean at all, because now this chunk of code has to deal with a “null possible situation” and take decisions that would not be supposed to be taken by itself.
The Null Object design pattern comes to work on this problem, basically, instead of returning null
where an object of class Foo
was expected, one could return an object of a subclass of Foo
in a basic valid state but at the same time, adhering to Foo
‘s contract.