Avoid Multiple Control Variables in For Loops
ID |
java.for_too_many_control_variables |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style, reliability |
Description
Reports classic for loops that declare more than one control variable in the init clause.
Rationale
A for loop with multiple control variables, such as for (int i = 0, j = 10; i < j; i++, j--), makes the loop invariant harder to reason about. Each additional variable introduces another dimension to track, increasing the likelihood of off-by-one errors, accidental infinite loops, or subtle logic mistakes. Loops are easier to verify when they have a single, clearly progressing control variable.
// Bad - multiple control variables
for (int i = 0, j = 10; i < j; i++, j--) {
process(i, j);
}
// Bad - three variables
for (int i = 0, j = 1, k = 2; i < 10; i++) {
compute(i, j, k);
}
Remediation
Refactor the loop to use a single control variable. Declare additional variables before the loop or compute them from the control variable.
// Good - single control variable, j derived
int size = 10;
for (int i = 0; i < size / 2; i++) {
int j = size - 1 - i;
process(i, j);
}
// Good - single control variable
for (int i = 0; i < 10; i++) {
int j = i + 1;
int k = i + 2;
compute(i, j, k);
}