简体   繁体   中英

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

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 = "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;
                }
              }
              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?

Replace enUSLabel = picklistLabel with return picklistLabel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM