Avoiding Null Anti Patterns

[CG]jupoulton
4,972 views
undefined

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
Previous: The Optional class

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 getTaxByCountry to return a passive NullTax instead of a null.
  • You must implement the apply method of the NullTax.

uml1

Implement the Null Object Pattern
// {...}
/**
* In this example, we apply a tax if the country is Denmark or Italy.
* We instantiate a different Tax object for each country.
* For all other countries, no changes to the price is made.
*/
public static double applyCountryTaxToPrice(double price, String country) {
Tax tax = TaxFactory.getTaxByCountry(country);
return tax.apply(price);
}
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.

uml2

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content