Saturday, December 12, 2009

a==1 or 1==a

I was in one of Dave Nagle's lectures at Carnegie Mellon in which he explained that he'd once spent an inordinate amount of time on a bug hunt. The cause: 'a=1' ... a typo. He meant to type 'a==1'. To insure he'd never suffer that pain again, he coded all his boolean comparisons with the literal on the left hand side, like this: '1==a'. This prevents the typo '1=a' because the compiler won't allow an assignment to a literal.

After going on the exact same bug hunt myself, many years ago, I kicked myself for not following his advice. I've coded all my Boolean expressions in the "literal on the left" style ever since, and the compiler has saved me many a bug hunt.

To that paradigm I now have a small addition to make. I've started coding my string equals comparisons in literal-left style as follows: "something".equals(a)

This has the nice effect warding off null pointer exceptions when a is null. I think this literal left style is better than (a+"").equals("something") which is another trick for warding off null values of a.

1 comment:

  1. I've recently been exposed to lots of code (PHP and JavaScript) where the original author adhered to your learned views of constant first.

    It took some time, as I am never a quick convert, but dealing with the foreign code has made me see the value of this syntax. If nothing else, it makes it very, very clear when reviewing code I didn't write.

    ReplyDelete