Null check coding standard [duplicate]

2019-01-27 07:27发布

问题:

This question already has an answer here:

  • Which has better performance: test != null or null != test 8 answers

I have a doubt regarding coding standard of a null check. I want to know the difference between

if(a!=null)

and

if(null!=a)

which one is better,which one to use and why?

回答1:

Both are same in Java, as only boolean expressions can be inside an if. This is just a coding style preference by programmer and most of them use null != a.

The null != a is an old practice in programming languages like Java,C++ (called as Yoda Conditions).
As it is valid to write if (a = null) and accidentally assign null to the a so writing null first is a guard to stop this accident from happening.



回答2:

There is no difference. But the first is more common. The second is also called "Yoda Conditions" because of its unnatural "grammar".

Once I was working in a project where the coding guideline was to use if (null != a) because they thought it is easier for the developer to understand that the constant value has to come first always (as in CONSTANT_VALUE.equals(variable). That was pretty annoying to me.



回答3:

They're both the same. It depends on your coding style.



回答4:

From the compiler's point of view, they're exactly the same. But the first form is more readable, so I'd advise you to use that one.



回答5:

No difference betwwen them if statement works based on result of expression so u write either if(a!=null) or if(null!=a) will produce true or false then result is evaluated.

So it doesnt matter you write which you like



回答6:

They both are same. Although the first variant is common the second variant is useful if you know the first variable is not null

Example "some value".equals(your_variable) , some value can be any value you know is not null. This will avoid NPE when your_variable is null.

String str = "somevalue"; 

if(str != null && str.equals("somevalue")) { }

if("somevalue".equals(str)) { }

Both the conditions will be same if str is null or not.