No semantic difference
if (null != thread) {
thread.interrupt();
}
Why the otherwise bright folks at Google wrote the null check in this backward way remains guesswork. I agree with you that it is harder to read than the natural thread != null
.
There is no gain whatsoever from the backward writing. The semantics are exactly the same.
Backward writing of an if
condition is known as a Yoda condition. Yoda conditions are debated, some say they have their place in some programming languages (like C) under some circumstances. In case of ==
rather than !=
for comparison you can read some of the arguments in the previously linked duplicate (I repeat the link at the bottom). In Java one might have a sought-after argument in a case like the following:
boolean b;
if (b == false) {
// Do something
}
Imagine that a programmer coming from Pascal or another programming language that uses single =
for comparison and putting single =
here by mistake. It would change the meaning to assigning false
to b
and never executing the conditional code. So the argument goes that by writing false == b
the compiler will catch such a mistake for you, which is a clear advantage. However:
Most compilers and IDEs do catch the mistake anyway. For example if I put a single =
in the above if
statement, my Eclipse says
Possible accidental assignment in place of a comparison. A condition
expression should not be reduced to an assignment
The if
statement would usually be written in the following way, which excludes any meaningful debate about a Yoda condition and is also generally recommended:
if (! b) {
// Do something
}
So going back to your question my guess is: A programmer at Google had the habit of writing Yoda conditions like null == thread
and by false analogy extended it to null != thread
too.
So does the order of != operands never carry any semantics?
For the sake of completeness, when I say that thread != null
and null != thread
have the same semantics, I am talking about this quoted code. In case of for example someObj.foo() != anotherObj.bar()
the order imposes an order of the two method calls. If both methods have side effects that interfere somehow, the order of applying those side effects may make a difference in some cases.
Links