2 ms·
Enumerating some techniques for avoiding NULL is useful, but it sidesteps the real issue. It is important that programmers understand that avoiding NULL will n
by mikekchar 11y ago
Enumerating some techniques for avoiding NULL is useful, but it sidesteps the real issue. It is important that programmers understand that avoiding NULL will not suddenly make your programs robust.
Generally speaking there is really only one case that you need to think about: what do you do when a function needs to return a value and it has no value to return. This often happens in error conditions, but it can also happen as a result of poorly designed code (for example the ubiquitous "doUpdate()" function that sometimes returns a result and sometimes doesn't, based on what was passed to it). I will maintain that initialization is a special case of this (I haven't initialized it yet, so I have no value to put in it).
However, more important than what you use to represent "I don't have a value" values, is what you do with it if you get one. In several of the examples in this article, a boolean is returned to indicated whether or not you have valid data in the parameters passed by value. This may seem "safe" because you don't crash, but there are often much more serious problems than crashing: data corruption, for example.
Let's consider the case where I gather some data from somewhere and write it to my database. In the case that my data collection failed, I certainly don't want to write random data that was returned in the parameter. What happens if the calling code neglects to check the boolean return value? This check is identical (and could literally be identical) to checking for NULL. The only difference is that if I try to an uninitialized, but valid data structure to my database, it will work. If I try to dereference NULL, it will crash. In many cases, crashing is preferred.
Even when you return a NULL Object, you still need to think very hard about what you want to do with it. What happens if someone tries to write a NULL Object to the database? We know things are very, very wrong. We could just skip it, but many times it would be prudent to halt execution of the program.
Too often I deal with programmers who blindly accept the advice that NULL is evil without actually understanding the problem that NULL is intended to solve. I have no problem with avoiding NULL (and in many cases it is a very good idea). It is important, though, to understand that you still have a lot to do to write robust code.
- tatterdemalion 11y agoThe problem with null is that its not a type error to use it as if it were a non-null value. What you want is for any code that could operate on invalid data as if it were valid data to be a compile time error.