Control Statement Braces

ID

java.control_statement_braces

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Best Practice

Language

Java

Tags

best-practice

Description

Reports if, else, while, for and do-while statements whose body is a single statement not wrapped in { }.

Rationale

Always bracing control-statement bodies has two benefits:

  • It prevents the "goto fail" / dangling-else class of bug: adding a second statement later silently drops it outside the control flow without any visual cue.

  • It lines up with debuggers: the braces introduce an explicitly-steppable line before the body, so the developer can see whether the branch was entered before the body expression is evaluated.

// Bad
if (x > 0) return;
while (x > 0) x--;
for (int i = 0; i < 10; i++) System.out.println(i);

// Good
if (x > 0) {
    return;
}
while (x > 0) {
    x--;
}
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}

else if is not flagged — the body of the outer else is already an if statement, not an open expression.

Remediation

Wrap the body in { }. Most IDE formatters can do this automatically across a codebase.