Null Object

Behavioral pattern

The Null Object pattern was created due to the need of avoiding the appearance of null values that can cause runtime errors. What this pattern basically proposes is using instances for implementing the required interface but with a void body, instead of returning a null value.

Null Object design pattern structure.
Null Object design pattern structure.

The components included in the pattern are:

  • Client: Component interacting with the potentially null object.
  • AbstractObject: Common interface between the real object and its null representation.
  • ConcreteObject: Class representing a real object, which has a concrete implementation; it will be created only when the requested object exists.
  • NullObject: Object which implements void methods. It will be created only when a requested object does not exist, and it’s going to be returned instead of a null reference.
Null object pattern sequence diagram
Null object pattern sequence diagram
  1. The client looks for a specific object.
  2. ObjectLookup checks if the requested object exists.
  3. If the requested object doesn't exist, an instance of NullObjectwill be returned.
  4. On the other hand, if the requested object is located, an instance of ConcreteObjectwill be returned.
  5. The client receives any of the two mentioned instances, however, it will never get a null reference if the object were not to be found.

Real-world example

By implementing the Null Object design pattern, we are going to develop an employee search service, which will avoid sending null instances whenever an employee is not found. If the requested employee is not found, a NullEmployee will be returned, that is, the null representation of an employee.

Discover how the Null Object pattern can help us solve this problem
Discover how the Null Object pattern can help us solve this problem

About this book

Introduction to design patterns

Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:

See book
All rights reserved ©
Reactive programming
LinkedinYoutubeTwitterFacebook

© 2021, Copyright - Oscar Blancarte. All rights reserved.