Design hint : introduce Null Object
I’m currently reading Refactoring from Martin Fowler. Overall, it’s an interesting book from which much could be said but tonight I would like to speak only of the “introduce Null object” hint provided in it.
The basic idea is pretty simple, instead of checking for null return from various call, just provide a “null object”. It means a real object but with no content. The clue is that this object knows how to handle method calls, rendering the right enum/int value/you name it according to its logic.
As such, no need to return null and then check for null everywhere. No result for search of Bla ? Simple, return the missingBla object !
Apparently it helped them quite a lot to skip of these redundant checkings, allowing as well to easily display objects full of others objects instances. Indeed, one instance being null is not an issue any more : calling person.getAdress() and then address.getStreet() providing now a missingAddress then a null street string. Some NPE may still appear, but way less than before apparently.
It’s the first time I see this hint and at first look it seems promising. Does someone have some second thought on it ? I’ll search more on it later on, maybe some caveats are known which would explain its relative anonymity !
NB : instead of using the term Null Object they use “missing object” apparently, which might avoid some confusions… Still on the “note side”, please note as well that the “missing objects” are always constant, making their usage pretty easy (and singleton like).
For resources, I found while writing this post that Martin provides a full list of each of the design hints he writes about, and even more (he provides updates and new ones). For the Null Object, it’s there, and probably better than my quick explanation. Great !
see ya !