Restricting the number of break
and continue
statements in a loop is done in the interest of good structured programming.
One break
or continue
statement is acceptable in a loop, since this allows optimal coding.
In most cases, they can either be combined together, or merged with the loop's condition.
The following code:
for (int i = 1; i <= 10; i++) { // Non-Compliant - 2 continue - one might be tempted to add some logic in between if (i % 2 == 0) { continue; } if (i % 3 == 0) { continue; } System.out.println("i = " + i); }
should be refactored into:
for (int i = 1; i <= 10; i++) { // Compliant if (i % 2 == 0 || i % 3 == 0) { continue; } System.out.println("i = " + i); }