Stupid question 40: Should I return 'null' or throw an exception if a methods fails to produce requested value?
Are you expecting a delivery or not?
This is very interesting as i had this discussion at work with a colleague just a couple of days ago, and Paul Blamire referred to that question in one of the comments on my previous post about how to return null from a generic method(give him a follow Twitter @pabloblamirez ). I started discussing this my colleague as I had a generic method that parsed json, the method would be mostly used in cases where I would expect it to produce a value- but not always. The ’not always’ (the method is a part of a helper class) made me decide on the return null, using default(T) (first I restricted it to classes, but realized that I wanted this method to return anything). Although fairly happy with my decision I think that this is a great question, and one worthy of a discussion!
My answer (and please do correct me if I am wrong!) is: (here is me talking to myself LOL )
I throw an exception if I am absolutely expect this to return a value, and handle it one way or another.
I return null if the method should be able to return null. If null would be considered an error, then I should have used an exception instead.
Any thoughts on this one?
I’ve gotten some great feedback on this one, and I’ve had a rethink about my approach. It makes more sense not to return null in dare I say most cases? Reading the arguments for and against I’ve come to the conclusion that for me it makes more sense not to return null, in most of the cases.
My new answer would be that I should write methods that are expected to return a value, and handle the exception if it fails to do so.
Quite a valuable lesson learned here for me, the biggest one so far from the ‘stupid’ questions. And maybe a valuable one for those reading this post, if you don’t ask and check whether your reasoning is right - even though you think the answer is given- you’ll never learn something new.
Last modified on 2012-09-08