Introduction
In this article, we discuss the null object design pattern.
Why do we need this pattern?
We all are familiar with null checks. The greater the number of null checks, the more the cyclomatic complexity. With the help of a null object design pattern, we can finally start bringing some sense to our null checks.
Let's start with a client class, which keeps the track of which smartPhone to sell. If SomeSmartPhoneMethod() returns nothing then SmartPhone class's object will be null.
In this case, the code might throw a null exception to the user.
- class SmartPhoneSale
- {
- SmartPhone OnePlus8 = SomeSmartPhoneMethod();
- static void Main(string[] args)
- {
- if (OnePlus8 == null)
- {
- throw new ArgumentNullException();
- }
- }
- }
Let's see how it looks conceptually:

As per our concept, we have already implemented a client class: SmartPhoneSale.
Now we need abstraction in our code. Let's go ahead and create that interface.
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace NullObjectDesignPattern
- {
- public interface ISmartPhone
- {
- string Name { get; }
- double Price { get; }
- }
- }
We need to concrete classes. One is for default initialization and another for our logic.
Let's create default class.
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace NullObjectDesignPattern
- {
- class DefaultSmartPhone : ISmartPhone
- {
- public string Name { get => "Please select smart phone first"; }
- public double Price { get => 0; }
- }
- }



Join the conversation! Your thoughts help the community grow.