Feb 17, 2011 12:57
Could somebody please tell me why
if 2 == x
something
is somehow preferable or more readable than the usual
if x == 2
something
To me the former is asking "Has the value of 2 been set to match x?"
Reminds me of the old saying, "2 can never equal 3, even for very large values of 2."
geek
Leave a comment
Comments 5
if (2 = x) won't compile
and
if (x = 2) will probably cause your program to die in horrible ways
That's the only non-stylistic reason I've seen.
Reply
Reply
On the other hand, if you use if "2".equals(foo), there's no risk of a null pointer exception (all OO languages safely handle null values passed as the argument to equals()), so your code is cleaner and automatically eliminates the exception risk.
Because of that, it's just considered good practice to be consistent and make all boolean comparisons involving a constant with the constant on the left side of the equation.
Reply
Hope you're feeling OK. I heard about the fall, and cringed in sympathy.
Reply
I probably could have just taken an extra painkiller and been good, given that I'd done similar things years ago with a prior foot surgery (and that was a FULL plant on the operated foot, without any damage). But given the effort the surgeon had to put into getting the foot properly aligned, I didn't want to find out a few days later that I'd hosed all his work. ;-)
Reply
Leave a comment