For code quality reason, I would like to refactor my code a little bit in order to use only one break
statement in my loop. But I am not sure I can do this the way SonarQube is aking me...
Here's my code :
for (Integer integer: integerKey.keySet()) {
if (map.containsKey(integerKey.get(integer))) {
TypeValue value = map.get(integerKey.get(integer));
sb.append(integerKey.get(integer)).append(":");
sb.append(encodeValue(value));
sb.append("|");
if (integerKey.get(integer).equals(min)) {
break;
}
} else if (integerKey.get(integer) <= min){
TypeValue value = map.get(min);
sb.append(min).append(":");
sb.append(encodeValue(value));
sb.append("|");
break;
} else {
sb.append(integerKey.get(integer)).append(":");
sb.append("0");
sb.append("|");
}
}
I would like to do the same thing but using only one break
but I am not sure I can write only one if
condition in this case instead of if-elseif-else
.
Any ideas ?
Thanks.
You could define a variable for the break-condition and include it into the for-loop condition:
boolean endLoop = false;
for (Iterator<Integer> keys = integerKey.keySet(); keys.hasNext() && !endLoop; ) {
Integer integer = keys.next();
if (map.containsKey(integerKey.get(integer))) {
...
if (integerKey.get(integer).equals(min)) {
endLoop = true;
}
} else if (integerKey.get(integer) <= min){
...
endLoop = true;
} else {
...
}
}
or declare a local variable in the loop which is set to true if the loop should left with a break:
for (Integer integer: integerKey.keySet()) {
boolean endLoop = false;
if (map.containsKey(integerKey.get(integer))) {
...
if (integerKey.get(integer).equals(min)) {
endLoop = true;
}
} else if (integerKey.get(integer) <= min){
...
endLoop = true;
} else {
...
}
if (endloop)
break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With