-
Notifications
You must be signed in to change notification settings - Fork 0
Description
Now, given that we have F.56 "Avoid unnecessary condition nesting", I would like to somehow change or remove the example in
ES.77: Minimize the use of break and continue in loops
Wording of today:
Often, a loop that uses continue can equivalently and as clearly be expressed by an if-statement.
for (int item : vec) { //BAD
if (item%2 == 0) continue;
if (item == 5) continue;
if (item > 10) continue;
/* do something with item */
}
for (int item : vec) { //GOOD
if (item%2 != 0 && item != 5 && item <= 10) {
/* do something with item */
}
}
I disagree that in the example above, the "loop that uses continue can equivalently and as clearly be expressed by an if-statement".
The code iterates over a vector, and there are a few exception where some items should be skipped. In my opinion the intent is obscured by rewriting the condition in an unnatural way, moreover introducing an unnecessary deep nesting, just to avoid a continue. Using a continue and cleaning up the condition would give code that adheres to rule F.56. Now, the following rewrite does not really fit in "avoid continue ". I think this a good way of using continue, instead of avoiding it.
//Good, follow rule F.56, avoid deep nesting.
for (int item : vec) {
if (item%2 == 0 || item == 5 || item > 10) // Sort of an early return, by using continue.
continue;
/* do something with item */ // Avoiding unnecessary deep nesting.
}