Avoiding Null Anti Patterns
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
- You must modify the method
getTaxByCountryto return a passive
NullTaxinstead of a null.
- You must implement the
applymethod of the NullTax.
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