Null Object Pattern For Avoiding Null Checks

I’ve had it on my todo list for a while to go ahead and look into the Null Object pattern. I vaguely recalled that it allowed you to return a null object and not have to actually test for things like:

if (employee != null && employee.isCurrent()) {
	employee.promoteOneLevel();
}

I see this all through a lot of java code to avoid the dreaded NullPointerExceptions (NPE). If a Null Object can clean up this sort of thing I’m all for it.

Essentially the trick is to implement a do nothing class like NullEmployee that implements the Employee interface, but all of its methods do nothing. In the case of isCurrent() in Employee, you just have the NullEmployee.isCurrent() method always return false. Pretty simple really.

I’m glossing over the details really and I need to spend a bit of time doing some more implementations. You can find more about it by Bobby Woolf, Martin Fowler, and Joshua Kerievsky.