Today, we will explore the details of the fourth design pattern. In our previous newsletters, we delved into the concepts of Decorator, Adapter and Facade patterns.
What is Null Object Pattern ?
This pattern says that when we come up with a situation where we are dealing with null value of some object, don’t throw NULL EXCEPTION. Rather return a object representing NULL value which acts as default value.
When we should use it ?
In .NET, you might consider using the Null Object pattern in the following situations:
When designing interfaces or abstract classes, you may want to provide default implementations for certain methods. Instead of returning null for methods that return objects, you can return a Null Object instance that provides default behavior.
In code where you frequently check for null references before calling methods or accessing properties, using the Null Object pattern can help simplify the code by eliminating these null checks.
If your codebase has many conditional statements to handle null references, employing the Null Object pattern can help reduce the complexity of such logic by providing a default behavior that is automatically used when dealing with null objects.
Using Null Object implementations can facilitate unit testing by providing concrete objects instead of null references, making it easier to set up test scenarios without worrying about null-related issues.
It's important to note that while the Null Object pattern can be useful in certain scenarios, it may not be suitable for all situations. Carefully consider the design and requirements of your application before deciding whether to employ this pattern.
Example
This is one of the most simple situation where we can see this pattern in action.
So when we come up with situation where Country is NULL we can return None instead of throwing Null Exception like this :
Thank you for reading, see ya next Saturday!
Whenever you’re ready, there are 2 ways I can help you:
Promote yourself to 9800+ subscribers by sponsoring this newsletter
Patreon Community: Join and gain access to the 200+ articles I have published so far at one place. Join here
Good reading