Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong in comparing a null with an object rather than an object with a null

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?

like image 953
Arif Nadeem Avatar asked Nov 28 '22 14:11

Arif Nadeem


2 Answers

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

like image 148
walther Avatar answered Dec 05 '22 11:12

walther


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
like image 26
John3136 Avatar answered Dec 05 '22 12:12

John3136