The Null Object

Listen to this post
Subscribe

Intent

Rather than using a null reference when an object is absent, create an object which implements the expected interface but whose methods have no behavior.

Many of the behavioral design patterns such as State and Strategy allow implementation to vary without specializing clients. Often when a behavior or algorithm has many different versions, one of those versions may be to have no behavior at all. To avoid putting special-case conditional code, “if(!null)” for example, into clients, a Null Object can be used.

Example

A system sends messages over a network socket. Sometimes these messages need to be encrypted in various way, depending on the client and/or receiver involved. The Strategy Pattern is used to hide this variation from the socket class. However, there are times when the data should be sent in clear text, with no encryption applied at all. A Null Encrypter can be used when this is appropriate.

Diagram

Null Object

Qualities and principles

Null Object eliminates null pointer checks in client objects, code which would otherwise be redundant. The fact that the algorithm in question is optional is encapsulated, which means it may not be optional in the future (making it open-closed) without any changes to clients. Null Objects are substitutable for all other versions of the behavior in question.

Testing

Typically, a Null Object requires no test since it has no behavior. However, a simple test may be written to ensure no behavior is inadvertently added to the object in the future.

Questions and concerns

A Null Object must have the same interface as the other implementations, but it is advisable to name parameters in such a way as to make it clear they are not used, like m(ignoreData d) or code to that effect. When a Null Object is used then the delegation from the clients to the service object is always made (it is reliable). Whenever there are reliable points of delegation from one object to another, this becomes an integration point for new behavior which often leads to the Proxy Pattern. A Null Object may also end a Chain of Responsibility.

More information

Visit the Net Objectives Pattern Repository: The Null Object Pattern

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.