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. Every call to makeAPoint()
needs to be checked, as shown earlier. This soon becomes tedious.
Note
The inventor of the null keyword called it his billion-dollar mistake!!! Please see http://www.infoq.com/presentations...