Java Reference
In-Depth Information
private static final DataElement createSentinel() {
// Allocate a sentinel object, setting all its fields
// to carefully chosen "do nothing" values
}
}
// Elsewhere
List<DataElement> 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 feasible, programmers should choose this design pattern over the explicit null
reference values, as described in Guideline 41 , “ Return an empty array or collection in-
stead of a null value for methods that return an array or collection .
When using this pattern, the null object must be a singleton and must be final. It may
beeitherpublicorprivate,dependingontheoveralldesignofthe 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, Volume 1,
Second Edition [Grand 2002], for additional information on this design pattern, and also
The CERT ® Oracle ® Secure Coding Standard for Java [Long2012],“ERR08-J.Donot
catch NullPointerException or any of its ancestors.”
Applicability
Leaving short-lived objects in long-lived container objects may consume memory that
cannot be recovered by the garbage collector, leading to memory exhaustion and possible
denial of service attacks.
Bibliography
[Grand 2002]
Chapter 8, “Behavioral Patterns, the Null Object”
[Long 2012]
ERR08-J. Do not catch NullPointerException or any of its ancestors
Search WWH ::




Custom Search