Date Published: August 20, 2020
The null object pattern is a simple pattern that attempts to reduce null checks in a program. You might also know it as the Stub, Active Nothing Pattern, or Active Null Pattern.
Head First Design Patterns by Eric Freeman and Elisabeth Freeman provides an brief synopsis of the Null Object Pattern in its sixth chapter.
Pluralsight's Design Patterns Library course has a module on the Null Object Pattern from David Starr.
Null checks are annoying, but they're very prevalent in many programs, and they can really clutter up your code. The purpose of the Null Object pattern is to provide an object that can be referenced instead of a null reference. This allows methods to be called on a variable that could be null without the program having to check whether that variable is null.
Using the Null Object Pattern can help declutter your code and decrease its complexity.
The null object pattern's implementation is pretty simple. First, you'll have an abstract base class for the object you're applying the pattern to. Inheriting from that class are one or more concrete, "real" implementations of the class, as well as at least one concrete null implementation. While the "real" objects will implement various
DoSomething() methods with actual effects, your null classes will implement those same
DoSomething() methods such that they actually do nothing.
As David Starr points out, it is common to implement the null object as a Singleton.
A few last points:
Thanks for reading! I hope you find this and other articles here at ilyanaDev helpful! Be sure to follow me on Twitter @ilyanaDev.