What is wrong in comparing a null with an object r

2019-06-26 09:05发布

问题:

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?

回答1:

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...



回答2:

Both are equivalent, but the null != object is an old practice from languages where it is valid to write if (object = null) and accidentally assign null to the object. It is a guard to stop this accident from happening.



回答3:

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


回答4:

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/



回答5:

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



回答6:

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).