Null Object pattern

From Wikipedia, the free encyclopedia

In object-oriented computer programming, a Null Object is a behavioral pattern designed to act as a default value of an object.

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; this tends to make code less readable. 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.

It 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[1] and Joshua Kerievsky's[2] 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[3]

[edit] References

  1. ^ *Fowler, Martin (1999). Refactoring. Improving the Design of Existing Code. Addison-Wesley. ISBN 0-201-48567-2. 
  2. ^ *Kerievsky, Joshua (2004). Refactoring To Patterns. Addison-Wesley. ISBN 0-321-21335-1. 
  3. ^ *Martin, Robert (2002). Agile Software Development: Principles, Patterns and Practices. Pearson Education. ISBN 0-13-597444-5. 

[edit] External links

Languages