github twitter email rss
Pattern: Null Object
0001 Jun 1
2 minutes read

Pattern: Null Object

  • if
    • An object reference may be optionally null and
    • This reference must be checked before every use and
    • The result of a null check is to do nothing or assign a suitable default value
  • then
    • Provide a class derived from the object reference’s type and
    • Implement all its methods to do nothing or provide default results and
    • Use an instance of this class whenever the object reference would have been null

Problem

Given that an object reference may be optionally null, and that the result of a null check is to do nothing or use some default value, how can the absence of an object — the presence of a null reference — be treated transparently?

Solution

Provide something for nothing: A class that conforms to the interface required of the object reference, implementing all of its methods to do nothing or to return suitable default values. Use an instance of this class when the object reference would otherwise have been null 

Gotcha

A NULL OBJECT should not be used indiscriminately as a replacement for null references. Its intent is to encapsulate the absence of an object where that absence is not profoundly significant to the user of an actual object. If the optionality has fundamental meaning that leads to different behavior, a NULL OBJECT would be an inappropriate. Any need for a runtime type query, such as an  isNull method, indicates that absence is significant rather than transparent, suggesting a  null rather than a NULL OBJECT
A NULL OBJECT can be used to complete many other common patterns and object structures: a null I TERATOR [Gamma+1995] goes nowhere; a null COMMAND [Gamma+1995] does (and undoes) nothing; a pointer to an empty function can be used to provide null callback behavior in C; a null collection is empty and cannot be changed; a null S TRATEGY [Gamma+1995] provides no algorithmic behavior, a generalization that extends to compile-time binding of template policies in C++, e.g. non-locking behavior for S TRATEGIZED LOCKING in a single-threaded environment [Schmidt+2000]; a null lamina can terminate LAYERS [Buschmann+1996], such as a null socket layer for a standalone workstation.

References

  • [Null Object Something for Nothing, Kevlin Henney March 2003]()
  • [The Null Object Pattern, Bobby Woolf]()

Back to posts


comments powered by Disqus