Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right position of literals in String Comparison?

Tags:

java

pmd

I have

if (localName.equals("TaxName")) {

but PMD says

Position literals first in String comparisons
like image 543
unj2 Avatar asked Jun 23 '10 20:06

unj2


4 Answers

"TaxName".equals(localName) is better as if localName is null you won't get a null pointer exception.

like image 126
Adam Avatar answered Oct 19 '22 00:10

Adam


PMD should also be telling you why it generates this warning. From the rules documentation on the PMD website:

Position literals first in String comparisons - that way if the String is null you won't get a NullPointerException, it'll just return false.

like image 30
matt b Avatar answered Oct 19 '22 01:10

matt b


I prefer to position literals first, i.e. :

if ("TaxName".equals(localName)) { ...

This way you do a right comparison for the case of null, instead of getting NullPointerException.

like image 5
Eyal Schneider Avatar answered Oct 19 '22 00:10

Eyal Schneider


Personally, that doesn't make sense to me. If the code catches a NullPointerException, then it's done work that you won't have to do later. If localName ends up being null, and that causes a problem later on, then it'll be harder to trace. Don't change code to make the compiler happy. If your code throws a NullPointerException, then it's saved you debugging time later.

like image 2
Melody Horn Avatar answered Oct 19 '22 02:10

Melody Horn