Checking for nulls? Not anymore

nullA huge pain in the arse for most developers is the need to null check everything before starting to use it. Microsoft has introduced null operators in previous versions of C# and upgraded them in C# 6.0 but still, we can and we should avoid them.

How? Well by avoiding nulls altogether.
Can we do that? Of course we can.

Let’s see how

Nulls can exist in our code in two possible cases:

  1. Null is a valid value in terms of our design contract.
  2. Null is not a valid value but somehow was created or returned.

The second case is easy to handle. When a null has appeared where it should not, the code should fail and it should fail big.
Throwing NullPointerException is big enough for me. If a null value should not by any way be existent in our code then an exception should be thrown and handled accordingly. This is commonly a sign of problems in your code since null is not an acceptable value and yet you receive a null value, so the preferable solution is to fail yes.
Now there are many ways to fail. You can throw an exception, let the program throw an exception on it’s own or use assertions.
Before you get really defensive about this failing is not bad, failing in this case is in fact good. As we pointed earlier, null is not an acceptable value in your contract so when a null is returned then there is a problem in your code. Failing is the only option to ensure that the code is corrected. The alternative? Null check EVERY possible object in your code to ensure that it is not null before accessing it. Useful? No. Since you are designing your software to not have null values in specific cases, there is no need to perform null checks on those specific cases.
In the following code would perform a null check after it?

No you would not. Why? Because the language contract (whether it is Java or C# does not matter in this case) ensures you that an object will be created and null will not be returned. If there ever is a case in which the above code returns a null value then the code should fail. There is no point in null checking things that are guaranteed to not be null.

So what about cases in which a null value is valid response in your design contract? Well they require special treatment.

.
But I will try to guide you to ways to change your contract in order to remove nulls without removing any functionality of your code.

  • Yoda Expressions

One way is to use yoda expressions (as we stated in a previous article) and putting the object that is guaranteed not to be null first in the evaluation similar to the following.

This way if object1 is guaranteed not to be null then no null check is needed. the two objects will not be equal so simply the if statement will evaluate to false.

  • Return empty Collections (Lists, Arrays, Arraylists, IEnumerables etc) not null objects

When a method is to return a collection of objects and in some cases you are returning a null value, instead of returning a null value, return an empty List. I know I know, instantiating a list costs precious time (especially in Java) and lots of memory (again especially in Java). But when you stop returning nulls then there is no reason to do null checks. If you wish to iterate through a collection there is no reason to nullcheck it first. You just try to iterate through an empty list and no iteration happens. Simple, effective, removes the need to check for nulls.

  • Use what the language offers
C# for some time now had the null coalescing operator (??) In a statement like the following

would return the result of the method call if not null or a new instance of MyObject in case the method returns null. So when running external code that you have no control over, in which the value null is a normal value, you can simply use the above method to remove further null checks in your code.
You can wrap that method call into another if you like to encapsulate this behavior if you’d like. It could look something like the following

 

So all following calls to the MyMethod method can be done through runMyMethod and so no nullcheck needs to follow it.

Groovy and C provide the Elvis operator ‘?:‘ (if you tilt your head to the side you can see the question mark as the trademarked Elvis hair). Which has the same usage as C#’s ?? PHP also supports ??

In Javascript, Python and Perl this can be achieved by a simple Boolean or operation. Since all these languages can transform any value to a Boolean type.

So you can simply do

If your value is null (or undefined), the variable smth will automatically be assigned the value of safeValue. If not it will be assigned the value of maybeNull. Due to lazy evaluation, the first is “truthy” (as Douglas Crockford says it) so it evaluates to true, and there is no reason to check the second statement.

C# 6.0 and Java 8 introduced new ways to cover the possibility of nulls.
C# 6.0 has introduced the ? operator for null checks.
See if we want to to do get a value like the following

If any one of the chain is null then the code will crash. Now as we said before if null value is not part of our design then it should crash. But if in any of those cases null is a an acceptable value or even in the worst case all of them might return a null value the you would have to check for each part in a row if it is null? That would be one HUGE if statement. Well in C# you could simply do this

If any object in the chain is null, then the chain execution stops and a null value is turned to x.

Java has something similar to the above using the optional keyword introduced in Java 8.
In Java 8 Oracle introduced the optional class. As per the developers of Java the optional can be used as a method return type replacing null.

In java Optional objects are basically empty objects when they are assigned a null value.  So the following code

So if maybeNull is in fact null (or actually an empty object) then a new Smth() object will be created and smthObject will be assigned to it.

  • Strings
Never ever return a null string. It is indeed pointless and all string manipulation methods that will be done on it (in OO languages) will in fact need to null check before anything is performed. You can easily avoid this by returning an empty string instead.  Then all equality, string tokenization etc will not throw a null exception.
For example

The above code will throw a NullReferenceException. If the string str was an empty string though, no exception would be thrown and the equality check would simply return false. The same thing would happen with a string.split method. On an empty string it would return an empty array, but with a null string it would throw a NullReferenceException,

Leave a Reply