Home > Custom Development, Extreme Programming > Eliminating the Null Checks

Eliminating the Null Checks

null
June 18th, 2013 | Ken Payson

Eliminating the Null Checks

Sometimes it feels like half the code in an application is concerned with checking if variables are null and yet still bugs come up as a result of null reference exceptions. What can we do about this? Is there a way to spend less lines of code worrying about null and more time worrying about the core logic of your functions? Yes there is and it’s simple – stop coding using null!
Stop assigning null to variables

Never “initialize” a variable to null. Only assign a value to a variable after computing what its value should be. Properties on objects can be null. Declared variables need not ever be null. If there is no value, there is nothing to be done with the variable.

Stop writing functions that accept and work with null values.

Null is not a value of any type. It is pointer. C# objects are reference types and are passed by reference. Value types can be made into nullable types, but unfortunately, it is not possible to take a reference type and say it cannot be null. This is a weakness of the type system. If you have a function that takes a string and you pass in an int, you get a compile time exception because there is a type mismatch. If you take the same function and pass in null it will compile. Why? It should be a type violation because null is not a string.

It is the responsibility of the caller to make sure that it is giving a function data. If the caller does not have a value needed by the function, it should not be calling the function at all.

The called function needs to know it has values to work with before proceeding with the core of its logic. If the developer cannot guarantee that the function will be called with good data (maybe because it is public api method) then the function should validate the input at the top of the function and throw an exception if the input values are null. If you are using .NET 4, the code contracts with contract preconditions work well for this. If you are below .NET 4 you’ll have to settle for writing if(myObject == null) { throw new ArgumentException();} If on the other hand, you can guarantee that your function will be called correctly, you may ignore the null checks all together.

Sometimes functions are written to take optional parameters. If the optional value is not supplied it is null. The function branches on whether or not the value is null in order to perform some additional piece of work. Functions written this way tend to grow and grow as new requirements come and more optional parameters and branching logic are added to the function. The better approach is to have overloaded versions of the function. Private auxiliary methods should hold common logic used by the over loaded methods to eliminate any code duplication. Now in the calling scope, we do not need to pass null into any method. We can call the version of the function that does exactly what we need.

Stop writing functions that return null values

The flip side of not taking in nulls, is not returning nulls.
If a function is supposed to return a list of things and there are no items to return, then return an empty list.
If a function is supposed to return a single item from some source, a database, cache, etc. and it is expected that the item will be found but it is not, then throw and exception. For example, if you are searching for an item by id, then in normal workflow, you will have a valid id and a match should be found. If a match is not found this is an exceptional case.
If a method might reasonably fail to be able to return a value then implement a TryGet version of the method that takes an out parameter and returns true or false. This is analogous to TryParse for integers or TryGet for dictionaries. In the calling scope, you will have something like this:

Widget widget;
If(TryGetWidget(someSearchString, out widget) {
//The widget will have a value. Do something with the widget
}
Else {
//The search didn’t find anything
}

Conclusion

It really is that easy to greatly reduce null checks and null exceptions from your code. Don’t assign null to variables and don’t write functions to take in or return nulls.
In general, it is the responsibility of a function to communicate its requirements and throw an exception if the requirements are not met. The calling scope has the responsibility of making sure that is passing acceptable values into a function and handle any exceptions that are thrown.

The ultimate goal would be to eliminate possible null from the entire call chain. If function A calls, function B, which calls function C and we know that function A never returns null, then we don’t need to check the values originating from A and going into C. Of course, in any real world system, there will be many places where methods you call may return a null. Don’t just pass these values along into the next function call. Stop the null chain.

Ken Payson is a Software Engineer at LogicBoost an Agile consulting firm based in Washington DC.

  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: