Avoiding Null Anti Patterns
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Null Object Design Pattern
Sometimes, it is possible to use a special Null Object to encapsulate the absence of an instance by providing an alternative that behaves in a suitably passive way. Basically, instead of using a null value, create an object which has no impact on anything. The object will also be able to provide information on why a non-standard value was returned, whereas a null value cannot.
In Java, the pattern consists of having an interface to represent the object you wish to manipulate, a Real implementation which acts normally, and a Null implementation which can be used normally but will do nothing.
In the following example, an instance of Tax is created with a vat and a country, both received from a miniature database in TaxFactory.
- You must modify the method 
getTaxByCountryto return a passiveNullTaxinstead of a null. - You must implement the 
applymethod of the NullTax. 
Going further
If you want several normal objects to inherit from your interface, you need to make the equivalent of RealTax abstract and have all the non-null objects inherit from it. This enforces the semantical difference between a RealTax and a NullTax.