No public method shall return null, this applies also to protected methods of non-final classes

A method from a different class that declares an ovject-type as return value shall not return null. Some in-depth discussion can be found in Tor Norbye’s Code Advice #9. The main argument is there that returning null is often deferring exception handling to the caller. The client has to write code to detect an exceptional condition.

Why not throwing in exception instead. Ricky Clarkson went in his response to the original post so far that he postulated that null-values are actually error values. I would not go so far, the NullObject pattern offers a deferred exception (that could still be treated properly by the client) or a runtime exception in case the client ask for more than he deserved.

NullObjects can be implemented very differently, depending on which “meaning” is intended. The classical NullObject is a static instance that implements some methods, perhaps by just throwing exceptions.

Recently I proposed a different NullObject. It occurred in our typesafe enum implementation (we keep backward compatabilty to Java 1.3):

class AnEnum extends OurEnums {
public static AnEnum valueOf(String s) {
try { return valueOf(AnEnum.class,s);}catch(IllegalArgumentException e) {return new NULL();}

Where NULL is an inner class that throws IllegalOperationException on any method, but equals that always returns false. This ensures that two different calls using the same or even different string return objects that are different. In the original problem the critical value was null (which is in our framework represented by an empty string; Oracle does so too, so it doesn’t help to distinguish on the Java side).

Another feature of the NullObject is that it has a proper type. All null are the same. If you have many methods that gave you a null, you cannot easily tell which “null” is the problem.