What is the Null Object Design Pattern?
It is often the case that we have to check if a variable is null before using it. If we query a model from the database it might turn out to be nothing. Therefore, we have to add an extra
if to check if it was the case.
The null object pattern introduces an alternative solution. We can use a dummy object that shares the same interference as the original but does not implement any behavior.
Our code gets cleaner and we can remove the “if”. The fewer “ifs” the better.
If a product with a given name exists, we will receive a proper model. Otherwise, null will be returned. By introducing a
NullProduct that has no behavior, we can simplify our application.
NullProduct will introduce only default behavior with no underlying logic. It will be returned by
ProductDAO if no model is found. Therefore, the return type of the
getProductByName method will always be of type
It is much better in many cases if some objects can do nothing. Most of the time, we do not want to use cache during development on our local machine. It could get really frustrating.
At the same time, we need to be sure that our software could be cached and everything will work in production.
Such a problem can also be solved by providing a dummy implementation of a cache component that does nothing and can easily be substituted with real ones.
If we are developing the application locally, all we have to do is configure the cache to use our dummy implementation.
- Can simplify code and remove conditional complexity.
- Can be helpful during development.
- Simplifies interface for clients.
- Can hide errors and create unexpected behavior if improperly implemented.
- Can over-complicate an application.
The full source code and some other patterns are available here:
- Robert C. Martin, Agile Software Development: Principles, Patterns, and Practices.
If you would like to check out some more Design Patterns, you can find them in the following articles: