views:

585

answers:

9

Possible Duplicates:
How to check for equals? (0 == i) or (i == 0)
Putting constants on the left side in comparisons?

Hi, Many a times in blogs and books, i have seen conditions in if statements like this:

if(0 == a.size()){...}

or

if(-1 == str.indexOf(ch)){...}

Is there any performance advantage in using integer literals on left hand side in conditions or is it just a style that some programmers prefer?

+25  A: 

It's so you'll get a compile-time warning, instead of a mysterious bug, if you inadvertently use the assignment operator = instead of the comparison operator ==.

Jim Lewis
I guess in java, it doesn't serve much purpose as conditions have to be Boolean type. Or are there specific cases wherein it is helpful in java too??
nash
@nash - it could be helpful if you use an explicit style `if (b == true)` and `if (b == false)`. But I don't see any benefit to preferring `if (true == b)` to `if (b)` and `if (false == b)` to `if (!b)`
R Samuel Klatchko
@nash: Correct, it doesn't serve much purpose in Java, or with any language/compiler that does decent "lint" stuff. The related `if ("foo".equals(variable))` instead of `if (variable.equals("foo"))` has some limited utility in that if `variable` is `null`, you get a false result rather than a `NullPointerException`. IMHO, neither case justifies the awkwardness involved, but that's opinion, not fact.
T.J. Crowder
Oh ,someone already gave a example belowi guess the case in which it may be beneficial in java is:boolean b = true;if(b = true). here if(true = b){...} will give a compile time errorBut as such programmers will usually use if(b) or if(!b)So this particular style seems to be from programmers with C background
nash
@nash - most Java developers consider `(b == true)` to be *bad style*.
Stephen C
Yeah! That is a very logical answer..
Bragboy
blimey i cant believe i've never thought of this. +1
Matt Joslin
A: 

It's just a stylistic thing, to avoid accidentally using assignment instead of equality. For instance, it's easy to say if (size = 0) instead of if (size == 0). On the other hand, if (0 = size) will cause a compiler error.

eman
`if (size = 0)` will also cause a compiler error in Java.
Jesper
+1  A: 

I think it's to avoid mistakes such as

if(a.size()==0){...}

being mistyped as

if(a.size()=0){...}

which turns an equality test into an assignment.

High Performance Mark
But in Java the latter won't compile either, since Java requires the condition of the `if` statement to be of type `boolean`, and an assignment like that does not return a `boolean`.
Jesper
Bully for Java !
High Performance Mark
+1  A: 

The main reason to do this is to avoid accidental assignment (using = instead of ==) in the case where one side represents a variable. Although the examples you give don't fit this description, putting literals on the left side is generally a good habit to develop, because it can never result in an accidental assignment.

pelotom
Agreed for the most part although I believe @Andreas_D's response above is worth noting as well. There are a number of potentially conflicting goals to try and attain when programming: readability, maintanability, extensibility, safety. Sometimes this is what makes programming more an art than science.
PP
A: 

My IDE warns be about possible mistype of ==, so I prefer the more natural way if (size == 0). That said for string comparison I always do if "this".equals(x) to avoid possible NPE errors at runtime. An IDE like IntelliJ will warn you about those as well - basically modern IDEs do so much heavy lifting that such defensive style is not that practical anymore.

Bozhidar Batsov
+7  A: 

In C it's possible to write:

if(size = 0){ ... stuff... }

And it will compile just fine, assigning 0 to size, and avoiding the if as size is now 0. However,

if(0 = size){ ... stuff... }

won't compile, as 0 cannot be assigned. It's basically a holdover from these roots, to get an error when accidentally typing '=' instead of '=='.

As I recall, java would give a compile time error if this were done for almost any datatype, as it doesn't autoconvert numbers to booleans in if statements. But

if(flag=true)

Might still cause interesting trouble. Not certain as I don't have a compiler with me.

CoderTao
if (launchRocket = true) { ... }
Victor Hurdugaci
+4  A: 

One reason to use this pattern is that it helps avoiding some nasty bugs (as the others already mentioned).

But one reason to avoid this pattern is that the code becomes much harder to understand. Let's think about implementing the requirement

return 'true', if the person is 18 years or older

My immediate reaction would be a direct translation to

if (age >= 18) return true;

And now we try the other pattern

if (18 <= age) return true;

To me it's an obfuscated implementation of the requirement (and honestly, it took my some minutes to find an answer for this pattern!)

We usually expect the test object and variables on the left side and the test value on the right. That's the way we speak (see the requirement above), that's how we learn it early at school (2+x = 4, x = ?). And reverting this makes the code just harder to understand.

Andreas_D
+1 for stating this pattern is harder to understand. I am a paranoid programmer: I tend to code very defensively as I believe I am my own worst enemy when coding. However I do avoid constructs that could be mentally difficult to parse (as a developer quoted in the book "Coders at Work" source code is for humans, compiled code is for computers). In Perl I never use "unless" for this very reason.
PP
@PP +1 for this coming from a PERL programmer :-)
seanizer
+1  A: 

Because once it costs $20 million, and popularly known as 20 million dollar bug. Read first few pages of "Deep C secrets" Book. Compiler will not generate error in typo error like if (a=0) while it will generate error in if (0=a), as it cannot assign some value to a constant.

Shrikant
A: 

It's typed this way because a lot of people come to Java from the C or C++ worlds and as a result still have bad habits ingrained into them by C's and C++'s sharp edges.

In C there are two problems that interact poorly: assignments are expressions and boolean tests can be any of a broad set of types. Thus is is possible in C to have:

...
int a;
a = 5;
if (a = 6)
{
  printf("This should not happen!\n");
}
...

The problem, of course, is that you've assigned 6 to a instead of checking of a was equal to 6. As a result of a lot of brain damage caused by tracking down these kinds of subtle bugs, a coding convention was adopted that put the rvalues on the left side of the comparison so if you accidentally assigned instead of compared the compiler would have a conniption and puke all over your screen:

...
int a;
a = 5;
if (6 = a)  /* THIS CANNOT COMPILE */
{
  printf("This should not happen!\n");
}
...

Fast forward a few decades and a programming language later. Java looks an awful lot like C or C++ at first glance so people assume that it works the same way. It doesn't. While assignment is STILL an expression in Java, boolean checks must be of type boolean. The expression a = 6 will have an integer type and thus the compiler will puke. You can therefore, in Java, cheerfully use the coding approach that more closely approximates the way you'd talk, but people have difficulty grasping this and instead import their C and C++ habits.

JUST MY correct OPINION