英文:
checking the condition in java leading to error
问题
我有以下的代码片段,在if条件下,我得到了声纳的发现,即在检查相等性时,字符串字面值应该放在左边。请指导如何解决这个问题。
final String aviid = avcMaster.getAVMaster().getAviiId();
if ((!aviid.equals("44")) || (!aviid.equals("55"))) { // ** Sonar问题 **//
final String defaultAiId = "88";
deviceElement.setAttribute("avi", defaultAiId);
}
else{
deviceElement.setAttribute("avi", aviid);
}
英文:
I have the below piece of code in which under if condition I am getting the sonar
findings that is Strings literals should be placed on the left side when checking for equality. Please advise how to overcome this.
final String aviid = avcMaster.getAVMaster().getAviiId();
if ((!aviid.equals("44")) || (!aviid.equals("55"))) { // ** Sonar Issue **//
final String defaultAiId = "88";
deviceElement.setAttribute("avi", defaultAiId);
}
else{
deviceElement.setAttribute("avi", aviid);
}
答案1
得分: 3
`String` 变量和 `String` 字面量之间的比较
- 在变量上调用方法:如果变量为 null,将会得到 `NullPointerException`
aviid.equals("44")
- 在字面量上调用方法:你不会得到 NPE,并且在变量为 null 时会得到 `false`
"44".equals(aviid)
Sonar 给出警告,因为对于它来说,得到 `false` 要比 `NPE` 好,但代码是由你决定的。
------------------------
另外你的测试是错误的,因为它将始终为真,因为不能同时拥有 44 和 55,其中一个将为真,你肯定是想要 `&&`,而且最好以另一种方式进行,这样就不需要取反。
if ((!aviid.equals("44")) && (!aviid.equals("55"))) {
并且为了更简洁(来自评论)
deviceElement.setAttribute("avi", aviid.matches("44|55") ? aviid : "88");
英文:
Comparison between String
variable and String
literal
-
calling the method on the variable: if the variable is null you'll get a
NullPointerException
aviid.equals("44")
-
calling the method on the literal: you can't get a NPE and you'll have
false
in case the variable holdsnull
"44".equals(aviid)
Sonar warns you because for it, it's better to get false than NPE
, but the code is your choice.
Also your test is wrong because it'll always be true, as you can't have 44 and 55 at the same time, one of them will be true, you surely meant &&
, also you'd better do it the other way you wouldn't need the negation.
if ((!aviid.equals("44")) && (!aviid.equals("55"))) {
And to do it shorter (from comments)
deviceElement.setAttribute("avi", aviid.matches("44|55") ? aviid : "88");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论