This rule raises an issue when a continue statement is used inside a loop.
The continue statement is an unstructured control flow mechanism that disrupts the natural flow of a loop. When used, it immediately
skips the rest of the current iteration and jumps to the next one.
While this might seem convenient in the moment, it creates several problems:
continue statements occur and what they skip, making it
harder to understand what code actually executes in each iteration.continue statements can interact with new code in unexpected ways, making
changes risky.Structured alternatives like if statements make the logic explicit and easier to follow. Instead of using continue to
skip certain iterations, you can use a conditional to execute code only when needed. This creates clearer, more maintainable code that’s easier to
reason about.
Using continue statements makes code harder to understand, modify, and test. While it doesn’t directly cause bugs, it increases the
likelihood of introducing defects during maintenance because the control flow becomes less obvious.
The impact is primarily on maintainability:
continue statementsReplace the continue statement with an if statement that inverts the condition. This makes the control flow explicit and
improves readability.
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // Noncompliant
}
System.out.println("i = " + i);
}
for (int i = 0; i < 10; i++) {
if (i != 5) {
System.out.println("i = " + i);
}
}