Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid using more than a single "break" statement in a loop?

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.

like image 928
hacks4life Avatar asked Sep 30 '15 14:09

hacks4life


1 Answers

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;
}
like image 60
wero Avatar answered Oct 18 '22 03:10

wero