Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
class DataElement {
  public static final DataElement NULL = createSentinel();
   // Dead flag removed

   // Other fields

  private static final DataElement createSentinel() {
     // Allocate a sentinel object, setting all its fields
     // to carefully chosen "do nothing" values
  }
}

// Elsewhere
ArrayList longLivedList = new ArrayList<DataElement>(...);

// Processing that renders an element irrelevant
// Set the reference to the irrelevant DataElement to
// the NULL object
longLivedList.set(someIndex, DataElement.NULL);

When using this pattern, the NULL object must be a singleton and must be final. It may be either public or private, depending on the overall design of the DataElement class. The state of the NULL object should be immutable after creation; immutability can be enforced either by using final fields or by explicit code in the methods of the DataElement class. See Chapter 8, "Behavioral Patterns, the Null Object,"€ of Patterns in Java, Vol. 1, second edition [Grand 2002], for additional information on this design pattern, and also ERR08-J. Do not catch NullPointerException or any of its ancestors.

...