Friday 22 June 2012

Why I whine about return null

You may hear me go crazy when I see a return null; statement in the code. Unfortunately I've learned it the hard way. Whenever you have a possible null pointer, you need to check for it and add another path of execution to handle it.

Look at this code:

Can you count how many extra paths are there because of the null check? 2 extra conditions, and 1 extra collaborator (The StringUtils) to check for a null string.

Now look at the next code.
Doesn't that seem more stable? It's not hard to avoid return nulls, but it takes some discipline.
If you're still not convinced, listen to the guy who invented the null pointers:
http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare

2 comments :

  1. I'm not 100% sure that returning an empty string will a difference. Of course, a not expected NPE won't happen, but there will be a check on the size of the returned string. In most of the cases the null is handled as an "error", but the empty string is not always and error. I suggest to use the null object pattern instead: http://www.clear.rice.edu/comp212/00-spring/handouts/week06/null_object_revis... With this approach it is pretty clear that an expected value hasn't been provided.

    ReplyDelete
  2. I absolutely agree! I just didn't want to mix that "rocket science" into the story just yet :D

    ReplyDelete

Note: only a member of this blog may post a comment.