Habilelabs-Logo
Blog

Handling Nulls in JavaScript Using Null Object Design Pattern

December 13th, 2019 . 3 minutes read
Blog featured image

The Null Object Design Pattern wraps up the null into its own object. Instead of having a null reference for some object, we wrap it into a NULL version of that object which will implement the same interface that of the object, i.e. same methods and properties.

According to a Paper on Null Object,

The intent of a NULL OBJECT is to encapsulate the absence of an object by providing a substitutable alternative that offers suitable default do-nothing-behavior. In short, a design where “nothing will come of nothing”.

We can use this pattern whenever we have the NULL object returned or checked against before accessing the properties of the object. It has a kind of do-nothing behavior on its methods.

Problem:

We often get a situation where we have to check if an object exists and then we need to get its properties/methods. This kind of code gets messy very easily in medium to large scale applications repeating itself all over the codebase.

Take a look at the code below, we have a very simple example of a greeting code where we welcome the user by name if the person’s name is set, else, we say it ‘Guest’.

Each time after retrieving the object, we are checking its existence before printing its name.

Solution:

Null Object Design Pattern will remove the need of having lots of checks for null throughout your code. Let’s rewrite the above code using this pattern.

At first, we create a null wrapper class for the Person class and later we instantiate the null class if the person is not found instead of returning null.

As we can see above, though this pattern requires you to add a bit extra code at the beginning, it can reduce the code length and minimize complexity a lot in long run, especially in large applications.

Conclusion:

When used wisely, the Null Object Pattern will make your program cleaner. It should be used where it needs to, overusing it may cause error/bugs harder to detect and fix.

A Null Object should not be used indiscriminately as a replacement for null references. It is intended to encapsulate the absence of an object where that absence is not profoundly significant to the user of an actual object. If the optionality has fundamental meaning that leads to different behavior, a NULL OBJECT would be inappropriate.

Null Object pattern is often implemented as Singleton as all Null Objects of a class will be identical so there is no need for new instances.

Give it a try in your own project next time. You can connect with us if you need consultancy on Node js. You can know about JavaScript Performance Pattern to improve its performance.

Hope you enjoy this post, if you have any query then let me know in your comments. Share this with your friends if you find it helpful.

Thanks!

Author: Habilelabs
Share: