sharp bites

standing on the shoulders of giants

Returning null vs. Empty Collection/Default Object

In a nice thread on the cli_dev list (formerly altdotnet) they discuss whether you should return null or an Empty Collection/Default Object when a query returns no results.

There is a more or less common approach I agree with of returning a null collection when your query yields no results, like in GetUsers(), being therefore able to iterate it with a foreach(User user in GetUsers()) witout having to use safe-guards.

I think Luke Breuer makes a good point too in this post when talking about retrieving a particular result:
I like null checks to actually have significant meaning. I’ve actually adopted a convention – GetAwesomeObject will return a valid object or throw; FindAwesomeObject might return null. The idea is that a NullReferenceException means you really screwed up somewhere – you have a glaring logic error, because you didn’t account for possible emptiness.

Comments