如何解决声纳问题 “正确性 – 在找到相等条件后,该方法继续循环”

huangapple 未分类评论46阅读模式
英文:

How to resolve the sonar issue "Correctness - This method continues a loop after finding an equality condition "

问题

String LOCALE = "locale";
List<Map<String, Object>> labelList = // coming for other class
...

public Object resolveData(String locale) {
    Map<String, Object> enUSLabel = null;
    locale = locale != null && !locale.isEmpty() ? locale : EN_US;
    
    for (Map<String, Object> picklistLabel : labelList) {
        if (picklistLabel.get(LOCALE).equals(locale)) {
            return picklistLabel;
        } else if (EN_US.equals(picklistLabel.get(LOCALE))) {
            enUSLabel = picklistLabel;
            break; // Added break statement here
        }
    }
    
    return enUSLabel;
}

修改后的代码在 enUSLabel = picklistLabel; 语句后面加了一个 break; 语句,以便在找到 EN_US 标签后立即跳出循环。

英文:

I have below code. All i wanted from the code is

  1. if supplied locale in the method argument is present in labelList, return it
    or
  2. check if EN_US is present in labelList, then return it
 String LOCALE = &quot;locale&quot;; 
 List&lt;Map&lt;String, Object&gt;&gt; labelList = // coming for other class
...
 public Object resolveData(String locale) {
 Map&lt;String, Object&gt; enUSLabel = null;
         locale = locale!= null &amp;&amp; !locale.isEmpty() ? locale: EN_US;
              for (Map&lt;String, Object&gt; picklistLabel : labelList) {
                if (picklistLabel.get(LOCALE).equals(locale)) {
                  return picklistLabel;
                } else if (EN_US.equals(picklistLabel.get(LOCALE))) {
                  enUSLabel = picklistLabel;
                }
              }
              return enUSLabel;
 }

I am getting sonar issue (at enUSLabel = picklistLabel;)

Correctness - This method continues a loop after finding an equality condition
This method continues with a loop, and does not break out of it, after finding and setting a variable in an if condition based on equality. Since continuing on in the loop would seem to be unlikely to find the item again, breaking at this point would seem to be the proper action.

How to correct it ? Is it possible in one for loop ?

答案1

得分: 0

return picklistLabel替换enUSLabel = picklistLabel

英文:

Replace enUSLabel = picklistLabel with return picklistLabel

huangapple
  • 本文由 发表于 2020年4月9日 15:18:59
  • 转载请务必保留本文链接:https://java.coder-hub.com/61115869.html
匿名

发表评论

匿名网友

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

确定