Tricked by short circuit operators
I am currently feeling suitably humbled, having fallen into a nasty coding trap. At least in this case it didn’t cause a major industrial disaster (please shoot me if I ever start work in the aviation industry!)
So just to make the humiliation public, the following was the cause of my disgrace – I had a test, similar to the below:
So that’s all OK, isn’t it, even if it isn’t particularly nice code? – if the string is null the first test will evaluate to false, and then the short circuit operator will prevent the other two tests from being evaluated. Hence a null pointer cannot occur.
Well yes. In fact, that is correct – the above works OK. My problem was that I duplicated and changed the logic, without thinking through the consequences, and introduced an or operator into the mix:
Looks similar, at a glance, and again the short circuit operator should prevent any null pointer. Or should it?
In fact in this case, no. It all goes pear shaped, and horribly so. The reason is to do with operator precedence. What actually happens is that since && has a higher precedence than ||, the way the compiler actually interprets the above is this:
which, if myString is null, becomes:
So the second of the myString.equals tests is still evaluated, and a null pointer results. Luckily these lines of code weren’t wired into flight control.
I think I had been lulled into a false sense of security by the short circuit operator construct. Well, that’s one more mistake I’ll never make again. But clearly, I needed to refresh my knowledge of the rules of operator precedence !
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Leave a Reply