I know there are already many articles in this topic, but sometimes looking into the codebase, I feel it is still not emphasised enough. This post purpose is to explain why null reference is undesired in clean code. I would like this post to clearly answer why „null” should be avoided if you care about quality of your code.
Returning null reference is a very bad practice and you should do as much as possible to avoid doing it in your code. Sometimes it sounds just right to return „null” from method which does not have any value to return in some specific case (e.g. no value found for given parameter). WRONG! Never do that! OK… in 99.9% cases do not do that.
These are few reasons using null in code is bad idea:
- it causes NullPointerException in runtime when not checked,
- checking each variable if it is null to avoid NPE, before actually using it, makes code much harder to read and understand,
- it is ambiguous (does this method return null because it haven’t found value for the parameter I’ve passed or because value for it is null?),
- class fields with null values encourage mutability of objects.
Just to sum up, this is what the inventor of null reference said about his invention:
„I call it my billion-dollar mistake.” – Sir C. A. R. Hoare
Fortunately there are some nice ways to achieve „null-less” code in Java:
- return empty collection instead (e.g. Collections.emptyList()),
- „Optional” in Java 8,
- „Optional” in Guava library (if you do not use Java 8),
- NullObject pattern.