0

I used to write a test statement of Java code like "anObject != null", but I found some people do this reversely like "null != anObject". So, What is the difference between them and which one is a better way in Java?

Jiaheng
  • 274
  • 2
  • 9

4 Answers4

7

Their reasoning is that if you accidentally forget the !, then you have an assignment instead of a comparison, which cannot happen the second way.

anObject = null assigns null to anObject, while null = anObject will produce a compiler error.

Jan Dörrenhaus
  • 6,581
  • 2
  • 34
  • 45
3

this is somewhat related to yoda conditions :

"the force".equals(myString);

avoids null pointer if myString is null.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
2

It's a style of how people compare expressions.

Do not use null != anObject as null is a constant and is considered a Yoda condition.

Always put the variable left hand side and the constant on the right.

Darren
  • 68,902
  • 24
  • 138
  • 144
  • 2
    It's not bad, there's no reason to avoid it... in fact there are advantages to doing this. – tckmn Jun 28 '13 at 13:53
  • 2
    @Doorknob - maybe not bad, but I wouldn't really say it's convention. I personally find it harder to read and evaluate but it is preference. – Darren Jun 28 '13 at 13:55
  • 1
    It comes down to personal preference. Ultimately nobody will get hurt if you code this way. And you may protect yourself from doing something accidental that has a severe consequence in your compiled code. On the other hand it doesn't read as naturally as the correct way. – PP. Jun 28 '13 at 13:56
1

From a compiled code point of view there is no difference.

However from a paranoid-programmer point of view it can prevent you from making the dreaded assignment bug.

e.g. if you mistype:

null = myObject

you get a compiler error because you cannot assign to constant.

However if you mistype:

myObject = null

the compiler will not complain. And you may release code that assigns null to your Object instead of testing for null.

PP.
  • 10,764
  • 7
  • 45
  • 59