The Null Object Pattern

Noticed this interesting article about the Null Object Pattern. Basically, it is the idea that the null/nil object could accept any message and return itself, rather than the more canonical approach of throwing an exception. This seems to lead to simpler, more elegant, code due to the lack of exception handling and null/nil checks. The trade off seems to be, you get generally simpler, more obvious, code at the expense of the occasional hard to track down bug.

I am not sure what I think about this but it does feel a bit like the debate around static vs. dynamic languages and in that debate I am firmly on the dynamic side of the fence because the subtle errors just do not seem to occur very often. Perhaps the subtle errors around null/nil do not occur often enough to warrant the checks we currently have.

[via: RCR 303]

2 thoughts on “The Null Object Pattern

  1. I like using this in Objective-C, though there’s one caveat: if you assign to a scalar variable the result of the message to nil the result is undefined (consfused? you may have to read that twice ;) I haven’t found it to be a nuisance and it wouldn’t really apply to Ruby anyways.

Comments are closed.