What is wrong in comparing a null with an object r

2019-06-26 08:53发布

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?

6条回答
趁早两清
2楼-- · 2019-06-26 09:26

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

查看更多
在下西门庆
3楼-- · 2019-06-26 09:27

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.

查看更多
叼着烟拽天下
4楼-- · 2019-06-26 09:30

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
查看更多
仙女界的扛把子
5楼-- · 2019-06-26 09:40

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/

查看更多
等我变得足够好
6楼-- · 2019-06-26 09:44

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

查看更多
神经病院院长
7楼-- · 2019-06-26 09:46

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

查看更多
登录 后发表回答