Null Object Pattern in C#
Today, we will explore the details of the fourth design pattern. In our previous blogs, we delved into the concepts of Decorator and Adapter design patterns 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.
public record Country
{
public static readonly Country None = new(string.Empty, string.Empty);
private Country(string name, string numericCode)
{
Name = name;
NumericCode = numericCode;
}
public string Name { get; private set; } = string.Empty;
public string NumericCode { get; private set; } = string.Empty;
}
So when we come up with situation where Country is NULL we can return None instead of throwing Null Exception like this :
public static Country GetCountryByNumericCode(string numericCode)
{
if (!string.IsNullOrEmpty(numericCode))
{
// Find from countries collection and return
}
return None;
}
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place