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 bookNull Object
Behavioral patternThe 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.
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.
- The client looks for a specific object.
- ObjectLookup checks if the requested object exists.
- If the requested object doesn't exist, an instance of NullObjectwill be returned.
- On the other hand, if the requested object is located, an instance of ConcreteObjectwill be returned.
- 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.