Avoid Explicit Null Checks

JAVING
Javarevisited
Published in
4 min readFeb 3, 2022

One of the more frustrating things about reading bad written code is that you have to mentally discard a lot of code just to find what is relevant. Who hasn’t at least once in his career at least found a huge large method full of duplications, boilerplate that does more than one thing? I could talk about code smells for the whole day but today I just want to focus on one code smell that is very predominant and is actually simpler to avoid than what many think.

Explicit Null Checks
An explicit null check is null validation on incoming parameters because of fear of a NullPointerException. This is not a nice practice because it adds noise to your code, it difficult code reading and violates SRP(Single Responsibility Principle). Let’s have a look at an example of null check.

Some people think, “but sometimes I have no choice but to do it.”.
Really? Let me show some alternatives that could be used depending on the circumstances.

Do nothing
One option is to just do nothing, the caller of the function, should be cautious and make sure not to pass a null. But if he does and this leads to a NullPointerException, this is a good way of knowing that the way that function is being used is wrong. But also the code in the function we are calling should never return null. Null checks are bad but returning null is also equally bad.

There are many things the called function could do to avoid returning null. If the exception appears this will at least prompt a conversation about if something is mandatory, why is not present? Perhaps more thought about system design is required.

Using assertions
The java keyword ‘assert’ can be used in combination with a boolean expression to stop the program execution by throwing an assertion error. While this seems like an interesting alternative to the if statement, assertions are disabled by default in java. They are a nice debugging tool for those who want to use them with care. Sometimes some programmers will enable them during a bug fix, but they will always be disabled in the production environment.

Null Object Pattern
The idea behind this behavioural design pattern is to use polymorphism to create null versions of an object(M.Fowler also refers to them as missing objects). These null objects will have a function called isNull(), which for the source class will always return false, but for the null object will return true. The client will be able to choose to pass a null object instead of a null, and this will avoid having to do an explicit null check in method().

Optional
Latest versions of java have a class called Optional that can be used as a way of avoiding returning nulls. It is basically an implementation of the null object pattern. By using optional on the client we can avoid passing a null.

Validators, IllegalArgumentException and Business Exceptions
If the caller of the function is out of our control and we cannot be confident on the value that will pass to our function there are other alternatives to the null check that maybe regardless of also being defensive are probably more business friendly and perhaps more informative.

Validators
I mentioned at the beginning that methods should not have multiple responsibilities. If for whatever reason we must do that null check or some other type of validation, we could delegate it to a validator object.

Sometimes this validator is also not seen as an smooth solution and probably an unnecessary dependency into the class. It could be replaced using the Decorator pattern. Basically a wrapper around the function being called by a decorating object. More information about the decorator design pattern in this article I wrote time ago: https://medium.com/javarevisited/can-you-please-wrap-the-gift-it-is-for-my-grandma-1a15da02f60d

Illegal Argument Exception
NullPointerException its not a very informative exception for the client. So if we decide that we are not going to do any kind of null check but we are still afraid of the null, perhaps we could just throw an IllegalArgumentException instead.

It is not a good practice to catch runtime exceptions(aka. Swallowing exceptions), since as you know, the program just carries on working. It is highly recommended that if you are going to do something like this, at least you add a Logger.log() statement to help the developer that will be debugging in the case there is some problem.

Bussiness Exception
As I just mentioned in the previous alternative Runtime exceptions are not a good thing to catch. Instead of that, we could use Business/Declared exceptions, which will mandate the caller function to get ready(by adding try and catch blocks..) for a potential fault.

As you see there are alternatives to explicit null check. The topic of the null checks is important since as clean coders and craftsmen of software we should care not just about if the code works but also about it’s readability and maintainability. There’s a huge fear of null in the industry and it is justified since null can cause catastrophic disasters but also this doesn’t mean that the first thing that we should do mechanically is to perform a verbose null check.

Think Twice Code Once

I hope you enjoyed this article, if you did please give some claps 👏 and/or share it with your friends in social media.

--

--

JAVING
Javarevisited

The present continuous form of “to program in Java”.