🤖

Null Object Design Pattern

Class
Behavioral Design Pattern
Text
Last Revised
Oct 5, 2024
Created
Oct 5, 2024 06:05 PM
Priority Level
AI summary
Null Object Design Pattern
The Null Object Design Pattern is a behavioral design pattern that provides a consistent approach for handling null or non-existing objects. It is especially beneficial when you want to avoid explicit null checks and instead offer a default behavior for objects that might not exist.

Problem:

In object-oriented programming, encountering null references is a common issue, especially when objects are returned as null or passed as arguments.
notion image

Solution:

Using conditional statements can help address this problem, but in a real-world project with thousands of classes and functions, managing null checks everywhere becomes challenging.
 
notion image
To mitigate this situation, we can create a NullObject class that provides default behavior.
notion image
notion image
 
NullObject -
  • provides an interface identical to AbstractObject's so that a null object can be substituted for a real object
  • implements its interface to do nothing. What exactly it means to do nothing depends on what sort of behavior Client is expecting
  • when there is more than one way to do nothing, more than one NullObject class may be required

Key Points:

  • The Null Object class is typically implemented as a Singleton. Since a null object usually lacks any state, its state remains constant, making multiple instances identical. Instead of creating several identical instances, the system can efficiently utilize a single instance.
 
Built with Potion.so