Rice University - Comp 212 - Intermediate Programming

Fall 2001

Lecture #29 - Null Object Pattern


The Null Object says,  "Just because I don't have anything and don't do anything, it does not mean that I am not smart.
By not having anything, I don't take up much resource and can be shared among many.
By not doing anything, I am doing the right thing."

Today's Topics

  1. Discussion of programming project #3: Tournament Tree.
  2. Null-Object Pattern.

Avoid checking for null

In much of the current programming practice, the special value null is often used as a flag to represent a gamut of different and often disconnected concepts such as emptiness and falseness.  This can result in a lot of confusion and complex control structures in the code.  In our view, null should only be used to denote the non-existence of an object.  null is not an object and has no "intelligence" (i.e. behavior) for other objects to interact with.  Therefore, whenever we work with a union of objects and discover that one or more of these objects may be referencing a null value, we almost always have to write code to distinguish null as a special case.  To avoid this problem, we should think of adding a special object, called the null object, to the union with appropriate behavior that will allow us to treat all object references in a consistent and uniform way, devoid of special case consideration.  This design pattern is called the null object pattern.

Examples


dxnguyen@cs.rice.edu
Copyright 2001, Dung X. Nguyen - All rights reserved.