2 ms·
NULL/zero is a very simple concept. It means the lack of something. C/C++'s equating of null/zero with false also makes great sense with you think of it this wa
by userbinator 11y ago
NULL/zero is a very simple concept. It means the lack of something. C/C++'s equating of null/zero with false also makes great sense with you think of it this way. Thus my personal belief is actually "avoid NULL, use zero instead."
program will fail in run-time. Sometimes it's not an acceptable situation, sometimes it just makes debugging other problems more complicated.
I disagree. If I were to make a list of all the bugs I had to find over the years, sorted by difficulty, a nullpo (usually caused by something else) would be near the bottom. They're quite obvious precisely because of the crash that occurs when they're used, and you can usually easily trace back to the origin of that value.
Seeing all these clumsy "solutions" that increase complexity just to avoid something so simple is both sad and somewhat amusing. It's a bit cargo-culty. E.g. if you use the "Null Object Pattern", with the example given you still have to presumably check whether the returned value is an instance of the null object or not... so not only do you still have to do the same thing you'd have to do if you'd just used a simple 0, you now also have to make an additional class and figure out how to compare with it. It's obfuscatory.
I think avoiding "NULL" makes as much sense as avoiding the number 0 - i.e., none, null, \0, nada, zilch. ;-)
- hawkice 11y agoYes, NULL means the lack of something. Very simple. But not having something when you think you do is by far the most common class of errors. So if you are always clear about the fact you either WILL have something or MAY have something (instead of it being hidden), you can write software that you are more confident in, and (hopefully) crashes with completely opaque errors less frequently. [This is why I happen to completely agree w.r.t. Null objects -- I don't see a point unless it means something extremely specific. Like, File openFile() could return a UnreadableFile null-ish object as an error code, but that seems worse than just having checked exceptions.]
- userbinator 11y agoBut not having something when you think you do is by far the most common class of errors. In all the things I've debugged that's almost never been the actual error, but rather a symptom of something else (running out of memory, failed file opening, etc.) that needs further investigation. In my experience the "check for null, skip processing and continue if a value is null" way is a far worse option since it causes errors to propagate further, whereas a crash is an unmistakable call to action.
- hawkice 11y agoDepends a lot on programming language. Stuff like that tends to end up in Exceptions, if you have decently useful exceptions available.
- dllthomas 11y agoI definitely agree that many of the proposed cures are worse than the disease.