4

I just found out that I can compare null with an Object like this,

if(null != Object)

Rather than comparing Object with null, like

Object != null

What may go wrong if use the former approach?

Is that legal? If not then why does compiler accept it?

Arif Nadeem
  • 8,524
  • 7
  • 47
  • 78
  • 3
    Why do you expect this not to work? – Konrad Rudolph Apr 20 '12 at 10:44
  • 1
    Nothing wrong with it, just a matter of taste really. Some prefer this and others prefer object != null. Personally I find Object != null easier to read. – Kell Apr 20 '12 at 10:44
  • if(null != object), null as an object is compared with another object.. and comparision reference is null insted of object – Arif Nadeem Apr 20 '12 at 10:48
  • @mirroredAbstraction No. Null as a *reference* is comapared to another reference. The part after .. is meaningless. – user207421 Apr 22 '12 at 23:02

5 Answers5

6

Most people say Object != null because it is what they are used to and so it is easier to read.

The best argument I've heard for null != object is to avoid bad expressions. e.g. to pickup a typo in if (var == 1)

if (var = 1) // this is valid C
if (1 = var) // this is not valid C
John3136
  • 28,809
  • 4
  • 51
  • 69
6

There's one thing wrong about it - readability. If you want to write a clean code, you should care about the way it will be read in the future. It needs to be obvious, what it does and why it does a certain thing. If you place the "Object" to the right of the evaluation, it becomes less apparent what are you really doing. Well at least in my opinion...

walther
  • 13,466
  • 5
  • 41
  • 67
2

It's just a matter of readability. If you can read your code out loud and it makes sense it is easier to understand. The second version is like Yoda-talk.. "null is not the object.." compared the "The object is not null"..

This same goes for giving your variables and methods good names.

A good reference site for writing readable code: http://www.cleancoders.com/

barsju
  • 4,408
  • 1
  • 19
  • 24
  • Do you mean Yoda-talk, as in Yoda Syntax? – willDaBeast Apr 20 '12 at 11:29
  • Right.. http://jamiethompson.co.uk/web/2010/05/20/yoda-syntax-a-php-design-pattern-for-if-statements/ Only it argues for why, it a good idea is... Maybe if your German.. – barsju Apr 20 '12 at 12:40
0

It is the same. It is almost like saying if 1 != 2. Does this imply 2 != 1?

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
0

The != operator behaves just as the test for equality operator == .

Ignoring any side effects in the expressions then (expr1 != expr2) and (expr2 != expr1) are exactly the same.

If Object is a variable (or constant) then (null != Object) is just as valid (although a little bit less readable).

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
Ole Tolshave
  • 291
  • 4
  • 9