Just noticed this come up on my Facebook news feed – how to code assignment statements when programming (not in T-SQL):

  1. if (foo == 4) then …
  2. if (4 == foo) then …

#1 is the most natural way to write the conditional expression, but has a *massive* potential for introducing bugs that are very, very hard to find. If the second '=' is omitted, the conditional expression suddenly becomes an assignment statement and evaluates to true. Nasty.

#2 is the best way to avoid such problems, even though it seems unnatural. If the second '=' is omitted, it becomes an assignment statement but the compiler will barf, because you can't assign a value to a constant. (Some languages and data types may be immune to this – so this isn't a blanket statement – it's certainly a problem in C++.)

#1 was the cause of several bugs that took me a while to find while working on the Storage Engine code – all C++. I always use #2.

PS if (foo = 4) won't compile in C# if foo is an int, but you can come up with weird cases that do compile and break. Who uses managed code anyway?!? ;-) (ok, no hate mail please)