The reversed-comparison trick: an argument against
It's a common recommendation to write comparison between variables and constants by putting the constant first. I.e., instead of:
It's better to write:
The argument is that if you accidentally type "=" instead of "==", the latter code will fail to compile, while the former will silently be wrong. I want to argue against this technique and open the matter for discussion.
My argument is very simple, and it goes like this. Writing the comparison in "reverse" requires a mental effort, because the mental process usually goes, "If x equals one..." not "if one equals x..." So, you need to remember to do something special when you make a comparison.
But if you have to remember to do something special, why not just remember to check if you've used the correct operator? This is what I do. Whenever I write a comparison, I check to make sure I haven't accidentally typed "=" instead of "==." It requires the same mental effort as reversing the comparison, while making the code a bit more natural.
Why is this superior? Because it works when you're comparing two variables as well. What if you wrote this:
Reversing the order will not help you catch a mistake in this case (and it's a very common case). However, the rule "Always check if you've used the proper operator" WILL catch the mistake. It covers all cases. In other words, the reverse-comparison rule is a cop-out -- it encourages you to be lazy and not check if you've used the proper operator. The problem is, it only works some of the time, while my rule works all of the time.
int x, y;
if(x = y) // Oops!
Now, argue with me.