Literal Comes First in a Comparison

This is the first in a series of "Strange Programmer Habits" articles. In each article we highlight a strange-looking construction that looks wrong at first glance, but has a legitimate purpose. You don't have to use this construct to be a decent programmer. You don't even have to agree with it's justification. But after reading this article, you'll hopefully understand what was going through the mind of the programmer that used the construction it describes.

Consider this JavaScript code:


   function foo( aString ) {
     if( ":error" == aString ) {
       handleError();
     }
   }

Why did the author of this code put the variable reference (aString) after the string literal (":error") ?

Likely so you wouldn't accidentally turn the comparison into an assignment.

Here, look at this code:


   function foo( aString ) {
     if( aString = ":error" ) {
       handleError();
     }
   }

Do you see the error? The programmer has accidentally dropped one of the equal signs in the comparison operator. You may have spotted the problem straight-away, but if this code was being edited at 4AM the day before a big demo… believe me, it would be hard to spot.

If we put the literal first and then forgot the extra equals sign, we would get an error. Go ahead and try it. Open up the javascript debugger in your browser and copy this code fragment into it:


   ( function ( aString ) {
     if( ":error" = aString ) {
       console.log( "looks like an error token." );
     }
   } ) ( "blarg" );

You should get a syntax error, which would clue you off that you forgot an equals sign. This is a programmer habit seen in most "curley brace" languages (C, C++, Java, Python, etc.)

When I first saw this I thought it was stupid. And then one day I got bit by the "mistyped == as =" bug and realized I wasn't perfect. I use this construction all the time now and don't worry about accidentally forgetting an equals sign.