Have you ever debugged a null
error? It’s like a void space. The error often doesn’t tell you anything. Null handling sucks the life out of developers.
Developers should stop returning null
. Modern programming languages have exceptions – use them.
There was a time when we avoided throwing exceptions, because exception handling is thought to be slow, and has other criticisms as well.
However, returning null
instead of throwing an exception is far worse.
Let me explain.
If you were tasked to write the implementation of this method to retrieve a user:
public User GetUserById(int id);
If the user with value of id
is not found, you are probably tempted to return a null
value.
But what is null
? Is it an invalid id
value (e.g. id <= 0
)? Is it because the user is not found? Is it because maybe the user record has been disabled?
In most cases I have come across, a null
return would mean that something erroneous has happened. “User does not exist” is an error!
All is fine if your team is disciplined and religiously handle null
across the entire application, but chances are very slim because it is quite difficult to consistently handle null
when built-in types (such as int
or double
) will never be null
.
Uncaught null
exceptions are terrible to debug, not only because the null
exceptions don’t tell you much, but also because it often requires back-tracing many lines of code to figure out how and why you got a null
.
Uncaught null
values are no different from uncaught exceptions, and if you have been writing code long enough you’ll know that null
exceptions are one of the most common exceptions you have to debug.
If a developer above had thrown something like UserNotFoundException
for the method/function above, life would be so much easier – even if it was uncaught. Making it a habit to throw an exception as part of input validation or error handling forces you to think about the error scenario and error message.
Null is bad for health. Null exceptions are like black holes. Null is less than nothing…
“What do you mean less than nothing? I don’t think there is any such thing as less than nothing. Nothing is absolutely the limit of nothingness. It’s the lowest you can go. It’s the end of the line. How can something be less than nothing? If there were something that was less than nothing, then nothing would not be nothing, it would be something – even though it’s just a very little bit of something. But if nothing is nothing, then nothing has nothing that is less than it is.”
E.B. White, Charlotte’s Web