Skip to main content

Pattern: NullObject

Instead of returning null , use an object which implements the expected interface, but whose method body is empty.

Purpose of .NET implementation

You want to log data into the application ( with an ILogger interface ).
You do not want to verify if the logger is null or not before logging.
You can use the Null Object pattern to provide a default implementation of the ILogger interface that does nothing when its methods are called.

Examples in .NET :

NullLogger

NullLogger example for Pattern NullObject

namespace NullObject;
internal class LogWithData
{
ILogger _logger;
public LogWithData(ILogger? logger=null)
{
// If logger is null, use NullLogger.Instance
// This is the Null Object pattern in action
_logger = logger ?? NullLogger.Instance;
}
public void DoWork(string message)
{
// Even if _logger is NullLogger.Instance, this line won't throw a null reference exception
// because NullLogger.Instance is a non-functional implementation of ILogger
_logger.LogInformation($"start work with {message}");
}
}

EmptyFolder

EmptyFolder example for Pattern NullObject
using System;
using System.IO;

namespace NullObject;
internal class EmptyFolderDemo
{
public static void DemoWithCreateNewFolder()
{
//start example 1
var env = Environment.CurrentDirectory;
var guid = Guid.NewGuid().ToString("X");
var fldEmpty = Path.Combine(env, guid);
//create empty folder
Directory.CreateDirectory(fldEmpty);
var files= Directory.GetFiles(fldEmpty);
Console.WriteLine($"files.Length:{files.Length}");
//end example 1

}
}

Download source

See Source Code for Microsoft implementation of NullObject

SourceCode Directory.GetFiles

Learn More

C2Wiki
dofactory
DPH
Wikipedia

Homework

When retrieving data( e.
g.
a Person with ID =-1 ) from a database , return a NullObject instead of null.
How you will verify that the object is a NullObject?.