Home > Uncategorized > Saying No to Nulls?

Saying No to Nulls?

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.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: