Luna Tech

Tutorials For Dummies.

Null Object Pattern

2022-03-12


0. What is Null Object Pattern?

Reference

Used to solve Null Check problem and make our code cleaner.


1. Implementation of Null Object Pattern

Example Code

Approach 1: Implement a NullPerson class inherited from Person

Approach 2: Add an interface and NullPerson will implement this interface


if (learner == null) return new NullLearner();

public interface ILearner
{
    int Id { get; }
    string UserName { get; }
    int CoursesCompleted { get; }
}

public class NullLearner : ILearner
{
    public int Id => -1;

    public string UserName => "Just browsing";

    public int CoursesCompleted => 0;
}

Summary

We can also give object properties a default value to avoid null checks.