Null Object Pattern in C#

Null Object Pattern in C#
Null Object Pattern in C#

The null object pattern is designed to handle the null exception of objects without implementing too many null checks in the application. This is done by identifying the behaviour that should occur when a null is encountered and declaring a default object for that instance that should be passed when a null object is encountered.
For instance, consider a shopping website that looks up users based on their user id:

Now imagine that elsewhere the application needs to display some details about the user that was found, such as their name, etc. We will need to be careful to check for null objects in the application:

When implementing a large amount of code, it’s very easy to miss a check, in which case a runtime null reference exception can occur.
To implement the Null Object Pattern, a static instance of User is created to represent the case of a “not found” user:

Then, wherever you would have a method that could return a null User, there you can return the static instance instead:

Once the Null Object Pattern is in place, there is no need to even have the local variables (UserName, UserId) shown in the example above, as they only existed because the user instance might be null. Therefore, their null checks are also not needed. Hence, client code will become simpler and will have fewer duplicated codes since these kinds of null checks are mostly present throughout the code in our applications.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Originally published at https://blog.webnersolutions.com on January 24, 2022.

--

--

--

Our team in Salesforce is very strong, with in-depth knowledge of Salesforce classic and Lightning development as well as the Service cloud.

Love podcasts or audiobooks? Learn on the go with our new app.

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
Webner Solutions

Webner Solutions

Our team in Salesforce is very strong, with in-depth knowledge of Salesforce classic and Lightning development as well as the Service cloud.

More from Medium

Top 10 bugs found in C# projects in 2021

A Deep Dive into C#’s CancellationToken

An antique typewriter with a page with the word “CANCEL” written on it.

How can a simple parameter save memory?

Looking into C# Property Patterns Performance