Lang
Blog

Handling Nulls in JavaScript Using Null Object Design Pattern

ByZishan
December 13th . 5 min read
Handling Nulls in JavaScript Using Null Object Design Pattern

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.

if (object != null && object.name != null)
   // do something with name

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’.

class Person {
   constructor(id,name) {
     this.id = id
     this.name = name;
   }
 }
 const persons = [
   new Person(1, "John Doe"),
   new Person(2, "John Papa")
 ]
 function findPerson(id) {
   return persons.find(person => person.id === id)
 }
 let personOne = findPerson(1)
 if(personOne != null && personOne.name != null)
 {
    console.log("Welcome, " + personOne.name)
 }
 else
 {
    console.log("Welcome Guest")
 }
 // Again in some other part of code
 let personOne = findPerson(2)
 if(personOne != null && personOne.name != null)
 {
    console.log("Welcome, " + personOne.name)
 }
 else
 {
    console.log("Welcome 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.

class Person {
   constructor(id,name) {
     this.id = id
     this.name = name;
   }
 }
 // Null person wrapper
 class NullPerson {
   constructor() {
     this.id = null
     this.name = 'Guest';
   }
 }
 const persons = [
   new Person(1, "John Doe"),
   new Person(2, "John Papa")
 ]
 function findPerson(id) {
   const person = persons.find(person => person.id === id)
   if (person)
     return person
   else
     return new NullPerson()
 }
 let personOne = findPerson(1)
 console.log("Welcome, " + personOne.name)
 let personTwo = findPerson(99)
 console.log("Welcome, " + personTwo.name)

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.

Thanks for reading!

Keep in touch with us for next blogs.

Share:
0
+0