Reputation: 818
Fixing sonar violations and got a warning " Equals Avoid Null:
String literal expressions should be on the left side of an equals comparison." for:
if (title != null && !title.equals("")) {
//rest of loop
}
I changed it to:
if(!("").equals(title) && title != null){
//rest of loop
}
Is that change okay? Will it fix the violation? Could somebody possibly explain to me why the original is a violation? I don't understand the issue and have read: https://sonar43.spring.io/rules/show/checkstyle:com.puppycrawl.tools.checkstyle.checks.coding.EqualsAvoidNullCheck?layout=false
amongst one or two other articles, but I stil don't see what the problem is...
Upvotes: 0
Views: 4535
Reputation: 19189
The warning is telling you that it's not sure that title
won't be null
. A literal, however, such as your empty string, can never be null by definition. And since equals
can handle null
as an argument you're avoiding a potential NullPointerException
by writing <literal>.equals(<somebject>)
. If you're not using title
within the if statement there's no need for further null-checking:
if(!"".equals(title)){
//rest of loop
}
However, since you're checking if something doesn't equal a literal it makes little sense to let null values pass through.
The docs also has this related note:
Also, it is pretty common to see null check right before equals comparisons which is not necessary [...]
Upvotes: 2