Always remove short-lived objects from long-lived container objects when the task is over. For example, objects attached to a java.nio.channels.SelectionKey
object must be removed when they are no longer needed. Doing so reduces the possibility likelihood of memory leaks. Similarly, use of array-based data structures such as ArrayLists
can introduce a requirement to indicate the absence of an entry by explicitly setting its individual array element to null
.
...
Note that all code that operates on the longLivedList
must now check for list entries that are null.
Compliant Solution (Use Null Object Pattern)
This compliant solution avoids the problems associated with intentionally null references by using a singleton sentinel object. This technique is known as the Null Object pattern (also as the Sentinel pattern). When feasible, programmers should choose this design pattern over the explicit null reference values. The issues are analogous to those described in MET55-JG. For methods that return an array or collection prefer returning an empty array or collection over a null value.
Code Block | ||
---|---|---|
| ||
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, NULL); |
...