SOLID & Design Patterns Interview Question #47
What is the Null Object Pattern?
Structural, Creational & Behavioral Patterns Mid-Level Intermediate
Quick Interview Answer
The Null Object Pattern supplies an object with neutral behavior instead of repeatedly checking for null. The null object implements the expected interface but performs a harmless default action.
Detailed Explanation
The Null Object Pattern supplies an object with neutral behavior instead of repeatedly checking for null. The null object implements the expected interface but performs a harmless default action.
It can simplify calling code when doing nothing is a valid behavior. It should not be used to hide a genuinely missing dependency or an error that should be reported.
Code Example
public sealed class NullLogger : ILogger
{
public void Log(string message)
{
// Intentionally does nothing.
}
}