I have a loop that I am testing a condition in but if the condition is not met then after the loop is complete, I want to execute another code block:
Boolean loopConditionNotMetFlag = true;
for (List<String> element : myList) {
if (isSomeCondition(element)) {
// do something
loopConditionNotMetFlag = false;
break;
}
}
if (loopConditionNotMetFlag) {
// Do something else
}
Is there better way to do this without using the loopConditionNotMetFlag flag or is this a valid use of a flag variable and not a code smell?
Devlinite is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
Python has a special for
… else
syntax just for that control flow pattern. So I’d say doing it like this in a language that doesn’t have special support is probably as good as it gets.