Tuesday, September 4, 2007

The Null Object

Today I read an interesting article about using a "null object" design pattern in object oriented programming to help avoid the NullPointerException. Rather than verifying that an object isn't null before doing something, as in:

if (myObject != null) {
   // do something
}

instead, create a special null object that implements the required interface(s) in a "null" way:

class NullObject implements MyObjectInterface {
   public String getLabel() {
      return "Null value!";
   }
}

Then, whenever you need to use a "null" default value, return your NullObject:

public MyObjectInterface getObject(String input) {
   if(input.equalsIgnoreCase("Apple")) {
      return AppleObject();
   } else if (input.equalsIgnoreCase("Orange")) {
      return new OrangeObject();
   } else {
      return new NullObject();
   }
}

Using this pattern frees us from all those if-statements to test for null objects.

Source:
Jeff Langr, http://www.developer.com/design/article.php/3697611

No comments: