Inexperienced programmers can teach you a bucket load more than experienced programmers. I was reviewing someone’s code recently when I came across something so nasty that I had to blog about it.
Their reasoning was along the lines of - “that code kept throwing NullPointerExceptions, and this was the only way to proceed.” When I asked the inevitable question of “why was that code throwing a NullPointerException?”, the answer was an uninspiring “I don’t know”. A few moments spent debugging revealed a bug - that the developer had cloaked with the try-catch block. Scary to say the least!
As I was regaining my composure,
Joel who was watching all this in the shadows piped “Never catch NullPointerExceptions”. And what golden words they were! Almost anywhere you catch a NullPointerException, you are probably cloaking a bug. You should hunt for the source of the problem rather than cloak it.
You could generalise that for all workarounds - not just those that involve catching unexpected exceptions. The golden words could be generalised as “Behind every workaround lies a nasty bug”. Doesn’t that sound too obvious to be told? I don’t know any more :-)As I was thinking about all this, I remembered something that I find extremely annoying about Objective-C. Any operation on a null* value results in another null value (rather than a NullPointerException). Thus in Objective-C, the code above would have the same effect without the try-catch block.
The reason I find this extremely annoying is that every time I introduce a bug involving nulls, they propagate far far away from the original source of the bug. No exceptions are reported, and hence everything seems to be functioning correctly, except it isn’t! The symptoms are button presses being ignored; generated fields being mysteriously blank; empty files being writen, etc. The list goes on and on.
The annoying NullPointerException is your friend :-)
*For the purists, Objective-C refers to null values as nil values.