Site Loader

This design pattern is intended to provide a more suitable alternatives solutions for those cases when a default behavior is needed and we want to avoid futures validations or errors because of a null reference.
Basically, it handles the null reference and turns it out in a new default concrete object that returns empties or defaults results using a Factory to handle that behavior.
You should use Null Object pattern when:
An object requires default behavior throughout all life cycle of the software when a null reference appeared.

Abstract the clients from the handling of the null reference.

Here is the basic diagram of this pattern:

Basically, this pattern is formed by:

IAnimal: Is an interface that helps us define the abstract class guide, you can do it without it.

Here is the example:

Animal: is the abstract class that held the null instance need to make the replacement when needed in the Factory.

Here is the example:

Cat, Dog and Cow: these concrete objects intended to act as the concrete object we want to handle, in our case we are simulating a Zoo animal’s sound and each one of those concrete objects makes the sound belong to them and if the animal doesn’t exist.

Here is the example:

Here is a complete example of the implementation: https://github.com/edgarleonardo/NullObjectDesignPattern

Post Author: Edgar Leonardo

I am Full Stack Developer and DevOps passionate, result-driven with deep experience on IT concerns. I am always seeking the best knowledge and practices in the world of technologies that make me and my work improve every day.

With more than 10 years of experience working as an IT professional, I have been involved and in some case leading large-scale IT projects since Backend, Frontend, Mobile Applications, Cloud Solutions and API integrations and even DevOps for Latam and the Caribbean in areas like Finance, Banking, Digital Advertising, Search engines, Social Network, Software Development, Outsourcing and Freelancer, integrations and more.