英文:
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
- if supplied locale in the method argument is present in labelList, return it
or - 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 ?
答案1
得分: 0
用return picklistLabel
替换enUSLabel = picklistLabel
。
英文:
Replace enUSLabel = picklistLabel
with return picklistLabel
专注分享java语言的经验与见解,让所有开发者获益!
评论