Please not another NullReference
March 25, 2014 Leave a comment
I’m just sitting in front of a piece of code. Only about 30 lines long it contains more than 10 checks for null
values. It is barely readable even after I combined some of these checks into methods with meaningful names. I don’t dare to think about what any complexity metric would tell me about it 😦
I know that inventing the Null Reference was one of the biggest mistakes in the history of computer science. But just because I know that doesn’t help me much when dealing with the aftermath of that mistake on a daily basis.
There are a few things that help though.
Never return null
!
Your methods should never ever in any case return null
! Ever! I mean it!
For strings there is string.Empty
.
For enumerations there is Enumerable.Empty<T>()
or the empty array T[0]
. If you use lists or collections (preferably represented by their respective interfaces) there is the (newly created) empty list.
For infrastructure components there is always some implementation of the NullObject Pattern (think about a NullLogger
that does not write anything anywhere).
For data objects you can define an Empty
property that contains an object that is valid in the sense of “I’m valid by the rules of your programming language” but that is defined as invalid by your business rules (think in terms of Guid.Empty
). Make sure to enforce the use of these properties. In addition to anything else it will make your code more readable.
For numeric IDs you should define a lower threshold for what is valid and what not. Usually IDs that are less than or equal to zero are not valid. They are just the default that .NET assigns to numeric types. Make that decision explicit! That way it is safe to check for invalid IDs anywhere you use them.
Oh and while I’m at it: Don’t throw NullReferenceExceptions when validating the parameters of a method. Use Guard classes that throw ArgumentNullExceptions or Code Contracts that throw their own special type of exception. NullReferenceExceptions are system exceptions and should stay that way.