Null check coding standard [duplicate]

2019-01-27 07:30发布

This question already has an answer here:

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?

6条回答
放我归山
2楼-- · 2019-01-27 07:55

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.

查看更多
疯言疯语
3楼-- · 2019-01-27 07:57

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

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-27 08:08

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

查看更多
劫难
5楼-- · 2019-01-27 08:08

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.

查看更多
贪生不怕死
6楼-- · 2019-01-27 08:18

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.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-27 08:19

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.

查看更多
登录 后发表回答