Accueil > Non classé > Design hint : introduce Null Object

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 !


Étiquettes : , ,
  1. Aucun commentaire pour l’instant.
  1. No trackbacks yet.

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:


Vous commentez à l'aide de votre compte Déconnexion /  Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion /  Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion /  Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion /  Changer )


Connexion à %s

%d blogueurs aiment cette page :