My boss said I should use null == obj
, because it's better than obj == null
, but he didn't remember why to do this. Is there any reason for using null == obj
?
After some search on Google, the only thing I found is:
in C, it prevents you accidentally from typing (obj = null) in a conditional structure.
You can't accidently assign null
to obj
by typing obj = null
instead. However, that's a reminiscence from C times, in java, it is not possible, as the =
expression returns the right hand side of the assignment. As null
is not a boolean
, the compiler will complain.
I would try to explain it to my boss once, demonstrate it. If he still doesn't agree with you, just do it. It's a petty thing to fight about with your boss.
If you compile your file with if(null==obj)
, the generated byte code is if_acmpne
and in case of if(obj==null)
it is ifnonnull
. Now in if_acmpne
two operands are popped out of stack and checked they are not equal(in this case null
and obj
), and in ifnonnull
, only one operand is popped and checked if it is not null. From this it seems ifnonnull
is better as it involves popping of only one operand.
References : http://www.artima.com/underthehood/flowP.html
In Java, there is no difference.
I prefer (obj==null) since it feels more natural.
If you do pass a condition as such if (obj=null)
or if (null=obj)
in present day java IDE's, it will highlight it as syntax error, In addition - attempt to compile will signal the error.
Both (obj==null)
and (null==obj)
are acceptable, they both carry the same overhead, the later do not yield any performance whatsoever. Decision to using either depends on code style adopted to maintain uniform style across classes.
I have never heard of this before, but it seems like the reasoning you gave is solid. I also think it feels backwards but, it should not have any issues other than "feeling" wrong. I don't think it would have any performance benefits or anything like that.
:)
One thing I've found useful about this is that the below syntax (absolutely valid from my POV) is not causing spotbugs
' DC-DOUBLECHECK
warning, allowing to raise spotbugs
threshold without any special exclusion etc:
if (defaultClient == null) {
synchronized (DEFAULT_CLIENT_INIT_LOCK) {
if (null == defaultClient) {
...
}
}
}
精彩评论