Archive for May, 2010

Saying No to Nulls?

May 5, 2010 Leave a comment

Have you ever finished working on a method and noticed the amount of code you wrote just to make sure that your code was safe from some object reference that could be null?

John Sonmez asked that very same question over at Elegant Code.

    The more elegant solution is to focus on never passing null.  By doing this you will end up writing less code and avoid decisions about how to handle null inside of a method that doesn’t have enough context to decide what to do.

    The context of his statement lies within the code that you, or your company owns (develops).

Robert Martin in his book “Clean Code” states that returning nulls is just as bad:

When we return null, we are essentially creating work for ourselves and foisting problems upon our callers. All it takes is one missing null check to send an application spinning out of control.

Neither author is stating some new revolutionary call to never check for nulls – rather, as far as long as it is in Your control, do not pass or return a null object.

Jon provides the following suggestions for initializing objects:

  • Initialize your variables when you declare them.
  • Use the Builder Pattern.
  • Use properties to provide default patterns.
  • Make your objects immutable

Robert suggest that throwing a null exception or returning a special case object as options. And, if you are working with a third party API where the methods return null, you can always wrap or adapt the third party’s API so that you have more control with it’s interaction with your code.

Categories: Uncategorized