If something is null in the program it means we have two paths one path on which we do something in the program when it is null another path is the one when it’s not null. The problem is this type of branching as soon as something is null, we must check that value everywhere to see if it is null or not.

Example

Null Object pattern helps to solve this problem. In Object Oriented programming one of the key things is replacing conditionals with polymorphism. We use objects because it allows us to use polymorphism. Consider an example where we have Animal Base class having speak method and subclasses Cat and Dog implement the Animal class and provide the implementation of speak method. If we were to achieve the same thing without using polymorphism like we don’t have Cat and Dog sub class instead we just have Animal, then we use conditional statements to know which type of Animal is passed and invoke respective methods. Polymorphism allows us to avoid that.

Now we can do the same thing when we have Null. In our example we can have a sub class NoAnimal which implements the interface Animal and provides implementation of the methods which essentially does nothing. This would sound like a simple polymorphism but in the hoods, it helps us to do things without using conditionals.

Now consider an example of a simple game where a person is running and there are obstacles on the path which can be avoided by using arrow keys like left and right arrow will move the person to the left and right, while up arrow will make the person jump and down arrow to crouch. Lets consider an interface IMovingBehavior which has definitions for the methods MoveLeft(), MoveRight(), MoveUp(), MoveDown(). This interface is implemented by MovingBehavior subclass which provides implementations for these methods.

Now let’s consider a case where we can supply powerups in the game and they can be good or bad. If a person gets a bad powerup we then must freeze the player. This is the case where we can have NoMovingBehavior which also implements the methods, but the implementation would be empty.

Null Object Pattern can be used in combination with other design patterns such as strategy pattern where we can have NoStrategy subclass which provides the default implementation. This pattern would be handy in places where we validate nulls using conditionals can now be replaced by polymorphism.

 

#15DayOf100DaysOfCode

Last modified: March 26, 2019

Author

Comments

Write a Reply or Comment

Your email address will not be published.