字符串比较中文字的正确位置是什么?

发布于 2024-09-06 22:51:06 字数 159 浏览 2 评论 0原文

我有

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

思慕 2024-09-13 22:51:06

"TaxName".equals(localName) 更好,因为如果 localName 为 null,则不会出现空指针异常。

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

花开浅夏 2024-09-13 22:51:06

PMD 还应该告诉您为什么它会生成此警告。来自 PMD 网站上的规则文档

在字符串比较中将文字放在第一位 - 这样,如果字符串为 null,您将不会得到 NullPointerException,它只会返回 false。

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.

赴月观长安 2024-09-13 22:51:06

我更喜欢首先定位文字,即:

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

这样您可以对 null 的情况进行正确的比较,而不是得到 NullPointerException。

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.

月下凄凉 2024-09-13 22:51:06

就我个人而言,这对我来说没有意义。如果代码捕获 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.

っ左 2024-09-13 22:51:06

为了避免该警告,一个更简单的解决方案是在之前检查空指针,建议在我们管理的每个对象中使用它,而不仅仅是在这种情况下:

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

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")) {
    ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文