Break statements and flags #
A method with multiple boolean flags can be complex to read and/or debug, in particular when combined with break
and/or continue
statements.
This can usually be avoided:
- using return statements (possibly with auxiliary functions), and/or
- (in Java) using streams with
anyMatch
,allMatch
orfindFirst
.
Example #
Rewrite the following Java method:
- without boolean flag and
- without
break
statement.
/**
* Returns true iff each of the input lists contains a number > 20
*/
boolean check(List<List<Integer>> lists) {
boolean flag1 = true;
boolean flag2 = false;
for (List<Integer> list : lists) {
for (int value : list) {
if (value > 20) {
flag2 = true;
break;
}
}
if (!flag2) {
flag1 = false;
break;
}
}
return flag1;
}
With an auxiliary method:
boolean check(List<List<Integer>> lists) {
for (List<Integer> list : lists) {
if(!isValid(list)) {
return false;
}
}
return true;
}
private boolean isValid(List<Integer> values) {
for (int value : values) {
if(value > 20) {
return true;
}
}
return false;
}
boolean check(List<List<Integer>> lists) {
return lists.stream()
.allMatch(l -> l.stream().anyMatch(v -> v > 20));
}