Null Object pattern

From Wikipedia, the free encyclopedia

Jump to: navigation, search

In object-oriented computer programming, a Null Object is an object with defined neutral ("null") behavior. The Null Object design pattern describes the uses of such objects and their behavior (or lack thereof). It was first published in the Pattern Languages of Program Design book series[1].

Contents

[edit] Motivation

In most object-oriented languages, such as Java, references may be null. These references need to be checked to ensure they are not null before invoking any methods, because one can't invoke anything on a null reference.

[edit] Alternate Patterns

Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach over a working default implementation is that a Null Object is very predictable and has no side effects: it does nothing.

For example, the processing of binary search trees, including operations such as insertion, deletion, and lookup, involves many nullity check of the encountered pointers. These checks can be implemented within the special object pattern.

The null object pattern can also be used to act as a stub for testing if a certain feature, such as a database, is not available for testing.

[edit] Relation to other patterns

It can be regarded as a special case of the State pattern and the Strategy Pattern.

It is not a pattern from Design Patterns, but is mentioned in Martin Fowler's Refactoring[2] and Joshua Kerievsky's[3] book on refactoring in the Insert Null Object refactoring.

Chapter 17 is dedicated to the pattern in Robert Cecil Martin's Agile Software Development: Principles, Patterns and Practices[4]

[edit] References

  1. ^ Woolf, Bobby (1998), "Null Object", in Martin, Robert; Riehle, Dirk; Buschmann, Frank, Pattern Languages of Program Design 3, Addison-Wesley 
  2. ^ Fowler, Martin (1999). Refactoring. Improving the Design of Existing Code. Addison-Wesley. ISBN 0-201-48567-2. 
  3. ^ Kerievsky, Joshua (2004). Refactoring To Patterns. Addison-Wesley. ISBN 0-321-21335-1. 
  4. ^ Martin, Robert (2002). Agile Software Development: Principles, Patterns and Practices. Pearson Education. ISBN 0-13-597444-5. 

[edit] External links

Personal tools