Introduce Null Object

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m
m
Line 15: Line 15:
  
 
[[Image:Null Object.jpg]]
 
[[Image:Null Object.jpg]]
 +
 +
* Create a subclass that acts as a null version of the class.
 +
* Create an isNull() method in both classes. For the superclass it should return "false", and "true" for the subclass.
 +
* Find all places that can give out a null value when asked for an object of the superclass and replace them to give a null object instead.
 +
* Find all places that compare a variable of the superclass type with null and replace them with a call to isNull().

Revision as of 03:11, 28 September 2008

Summarised from Refactoring Martin Fowler 1999

Motivation

You have repeated checks for a null value

For example your code my look like:

if (customer == null) plan = BillingPlan.basic();
else plan = customer.getPlan();

Solution

Replace your check for a null value with a null object

Null Object.jpg

  • Create a subclass that acts as a null version of the class.
  • Create an isNull() method in both classes. For the superclass it should return "false", and "true" for the subclass.
  • Find all places that can give out a null value when asked for an object of the superclass and replace them to give a null object instead.
  • Find all places that compare a variable of the superclass type with null and replace them with a call to isNull().
Personal tools