Java Behavioral Design Patterns – Null Object Pattern

The Null Object Pattern is one of the behavioral design patterns, it is an object with clear neutral or null behavior. It is called as Null object because by default it does nothing and only it helps to avoid NULL Pointer Exceptions.

In Object oriented programming we have to take care of Null Pointer Exceptions which are due to the absence of an object. In this pattern, we make sure that an empty, not null object is returned for processing, e.g. an empty list.  The calling function may simply iterate the list as normal, effectively doing nothing.

You can opt for this design pattern if your application:

  • Needs to streamline the NULL handling in your application.
  • 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.

Null Object Pattern by Example

Let us see this pattern using a simple Shop and Product example. The example contains:

  1. Abstract Class: The abstract class has to define the abstract primitive operations which are defined by the concrete implementations.
  2. Concrete Class: The Real Class is responsible for implementing the Abstract class, performing some real operations.
  3. Null Class: The Null class implements the abstract class, with empty logic.
  4. Client: The client receives the implementation of the abstract class and uses it

First, we will define a simple abstract class

After this let us add a concrete class, which provides some sample implementation

As mentioned earlier, Null Objects are the ones which are meant to avoid Null Pointer Exceptions by providing No Logic or Bare Minimum Implementation

We will add a simple factory class which will return us the Product object. It could be an actual product or a Null Object.

Running the Example

Above is example running our Null Object Pattern example.

Output

Conclusion

In this article, we understood Null Object Design Pattern with the help of a simple example.  This pattern saves many efforts which are generally wasted to check for null values. This pattern makes the client code very simple by avoiding unnecessary null checks.

The source code is available in our Github repository.

Download Code

 

Add a Comment

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