Null Object

A null pointer is used often as a way to signal to the client code that a called method could not return any valid object to its request.

This makes sense, but if the client forgets to check about the validity of the returned pointer there could be catastrophic results such as a null point exception. The Null Object Idiom (or Pattern, if you like) copes with this issue.

You can read more on this argument in chapter six of Head First Design Patterns where the Null Object Idiom (or Pattern) is introduced as an aside when discussing the Command Pattern.

Let's say we have a method that returns an object of a class derived from the interface Base or, in case no actual object could be generated, just a null. And let's say out client code should get a Base-derived object and then call a method on it. The usual code we write in this situation is something like this:
// ...
Base base = factory.create(/* ... */);
if(base != null)
    base.doSomething();
//...
The nuisance here is that we should pollute the code with checks against null, and the logical error deriving from forgetting it once somewhere is difficult to track down, since that the code is still working correctly. Almost always.

Often we can simply remove the use of checking against null, at the price of returning the instance of a fake class, when nothing sensible could be returned.
public interface Base {
    public void doSomething();
}

public class NullObject implements Base {
    public void doSomething() {}
}

public class Factory {
    public Base create(/* ... */) {
        switch /* ... */ {
        // ...
        default:
            return new NullObject();
        }
    }
}
In this way we don't need anymore the check against null:
// ...
Base base = factory.create(/* ... */);
base.doSomething();
//...
If we still need to know in the client code if we are working with a real object or the null one, we could always check its type through the instanceof operator.

No comments:

Post a Comment