Are you returning null from your methods? Are you branching your code with "if not null"? Do you often see null reference exceptions in your production logs? Read on to understand how you can design to completely avoid null in your codebase.
Sir Tony Hoare, a British computer scientist who invented the null reference in 1965, famously called his invention a billion-dollar mistake.
If you are writing any object-oriented code, you should deal with objects, not nulls. The Null Object pattern is one of the simplest design patterns, yet it is underused.
Imagine you are displaying all the associate information of a major law firm, "Pearson Hardman, " in New York City. Since Pearson Hardman only hires from Harvard, you are also gathering graduation data for all these associates from the Harvard data store.
Assuming all the associates are, by default, from Harvard, you have just returned null to the caller for the scenario where the Harvard service does not return any data for a particular associate. However, one of the associates, Mike Ross, never graduated from Harvard or any law school for that matter. Since the caller of the method 'GetStudentDataByName' expects a valid LawStudent object, they wouldn't validate for any null reference. The result is a null reference exception at runtime when trying to display the data for Mike Ross
public class HarvardRepository
{
public IHarvardStudent GetStudentDatabyName(string studentName) =>
//Mocked data pretending to fetch from the Harvard datastore
studentName switch
{
"Kyle Durant" => new LawStudent(
studentName, 3243, "A", new DateOnly(2011,4,30).Year),
"Harold Gunderson" => new LawStudent(
studentName, 3433, "B", new DateOnly(2012,4,30).Year),
_=> null
};
}
By following the Null Object Pattern, you can model your domain with objects, even for edge cases, rather than cluttering your codebase with nulls. As shown in the example, one way is to abstract out the LawStudent concept and model the domain with a specific implementation like 'DidNotAttendHarvardLawStudent' to represent Null.
public class HarvardRepository
{
public IHarvardStudent GetStudentDatabyName(string studentName) =>
//Mocked data pretending to fetch from the Harvard datastore
studentName switch
{
"Kyle Durant" => new LawStudent(
studentName, 3243, "A", new DateOnly(2011,4,30).Year),
"Harold Gunderson" => new LawStudent(
studentName, 3433, "B", new DateOnly(2012,4,30).Year),
_=> new DidnotAttendHarvardLawStudent(studentName)
};
}
By the way, the names and context in the above example are from a popular Netflix series. It is an easy guess though :)