开发者

What is the right position of literals in String Comparison?

I have

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

but PMD says

Position lite开发者_JAVA百科rals first in String comparisons


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


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.


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.


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.


To avoid that warning, a simpler solution is check nullpointers before, wich is recommended in every object we manage, not only in this very case:

if (localName!=null && localName.equals("TaxName")) {
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜