在Java中检查条件导致错误。

huangapple go评论68阅读模式
英文:

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 holds null

      "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");

huangapple
  • 本文由 发表于 2020年4月7日 19:26:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/61078939.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定