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

For reasons of code quality, I would like to edit my code a bit to use only one statement breakin my loop. But I'm not sure I can do it the way SonarQube helps me ...

Here is 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, but use only one break, but I'm not sure that I can write only one condition ifin this case instead if-elseif-else.

Any ideas?

Thanks.

+4
source share
3 answers

You can define a variable for the break condition and include it in 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 {
        ...
    }
}

, ​​ true, :

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;
}
+3

, .

0

@hacks4life, , , , , , " " ( , SonarQube , , ).

, . , (. Spaghetti_code).

, , , break ( ).

0
source

Source: https://habr.com/ru/post/1609650/


All Articles