Null reference exceptions considered harmful

Making a call to a service and getting a null result usually throws me, and when it throws me it usually means my code is about to throw an exception. This case applies especially to null instances of collection types.

Why would you want to return null for a collection? I can’t think of a good scenario where an empty collection wouldn’t work just as well. I consider this as an example of the Null Object Pattern.¬†Instead of a null reference, you provide an instance that works in place as an “empty” or default object. With C# you can use the LINQ method Any to check if a collection is empty: if (!serviceResult.AllAccounts.Any()) { … }. This is concise and readable, but if you start passing null references around then you have to make a potentially redundant check: if(serviceResult.AllAccounts == null || !serviceResult.AllAccounts.Any()) { … }. This is less readable and more error-prone.

I know that some would argue for the null-checks in the spirit of “defensive coding”, but I believe this goes against a standard principle: DRY (Don’t Repeat Yourself). By potentially returning null, the service is forcing all of its clients to check for null. This is duplicating code and raising the potential for error if a client misses it.

I’ve started to create implementations of the service’s interface that wrap the real service and simply replace collections with an empty instance if they’re null. This means that within the bounds of my application I can be sure that the service I’m using will never give a null collection. This is a form of defensive coding, but it is done in only one place and hence frees the rest of the application that uses the service from this burden.

Of course this would be a fairly moot discussion if we were using a language that prohibited, or at least discouraged use of null references, such as F#.

Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s