字符串比较中文字的正确位置是什么?
我有
if (localName.equals("TaxName")) {
,但 PMD 说
Position literals first in String comparisons
I have
if (localName.equals("TaxName")) {
but PMD says
Position literals first in String comparisons
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
"TaxName".equals(localName)
更好,因为如果localName
为 null,则不会出现空指针异常。"TaxName".equals(localName)
is better as iflocalName
is null you won't get a null pointer exception.PMD 还应该告诉您为什么它会生成此警告。来自 PMD 网站上的规则文档:
PMD should also be telling you why it generates this warning. From the rules documentation on the PMD website:
我更喜欢首先定位文字,即:
这样您可以对 null 的情况进行正确的比较,而不是得到 NullPointerException。
I prefer to position literals first, i.e. :
This way you do a right comparison for the case of null, instead of getting NullPointerException.
就我个人而言,这对我来说没有意义。如果代码捕获 NullPointerException,那么它就完成了您以后不必执行的工作。如果 localName 最终为 null,这会导致稍后出现问题,那么将更难以跟踪。不要为了让编译器满意而更改代码。如果您的代码抛出 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: