Null Objects – singletons in another garb

One popular form in which singletons are used is the Null Object pattern. Let's see what a Null Object is.

Java gives us the null reference to indicate a missing value. We are not supposed to call a method on it as there is no object. If, erroneously, we do, we are greeted with a Null Pointer Exception (NPE). When we design methods to return nulls, the client code that calls the method needs to check assiduously. This is what a typical null check-based Java code looks like:

       Point p = makeAPoint(); // a method that returns null in some cases
       if (p != null) { // the dreaded null check – onus is on us...
            // We are on sure grounds
       }

The problem is that the onus term is on us to check for a reference being null. ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.