Many times functions accept object references that can be null, and we tend to add if statements to treat the special case where null is passed to a function, and either provide a default response or do nothing. In the following example our calculateSpeed function expects an object that has a getSpeed function. In Javascript we will have to do something like:
But there is a better way to achieve that. Using the Null Object Pattern we can create a class that acts as vehicle, lets call it DefaultMovable.
Our DefaultMovable class provides the default functionality (aka the else in our previous code snippet), that way we can avoid the if/else statement.
The UML diagram of this pattern will look like this:
The same example in Ruby would look like:
This is just a pattern and as every pattern it has its pros and cons, apply it thoughtfully based on your use case. (The example is fictional for the shake of demonstrating the pattern)