Design Patterns: Null Object

Well, let’s start from the beginning! Sir Tony Hoare is who created the null reference, in 1965. Unitl now, Null checks is completly a requirement when we develop something.

Normal Situation

It is usually that we very commom we see null checks, like this:

public void CreateClient(IClient client)
{
if (client == null) throw new NullReferenceException();
if (client.Name == null) throw new NullReferenceException();
// ... do something
}

Null Object Pattern

First, we need to define a default object:

public class NullClient : IClient
{
public int Id => 0;
public string Name => "Non-client"; public int Age => 0;
}
static void Main(string[] args)
{
IClient client = new Client();
var clientService = new ClientService(); if (client == null)
client = new NullClient();
clientService.CreateClient(client);
}

Bachelor in Computer Science, MBA in Software Architecture and .NET Developer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store