If On Closing Brace Line
ID |
java.if_on_closing_brace_line |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
control-flow, readability, reliability |
Description
Reports an if statement that starts on the very line where the immediately preceding sibling statement — itself an if (with or without a trailing else) — ended. The two statements end up sharing a line: a closing } from the first, immediately followed by if from the second.
Rationale
A reader scanning the left margin sees a single decision and reads the second condition as an else if, because a closing brace on that line is exactly what an else if normally follows. In fact the two are independent statements: both conditions are evaluated, and both bodies run whenever both hold. If the author meant the conditions to be exclusive, a missing else is a live bug that the layout hides; if they were meant to be independent, the layout hides that the first branch falls through into the second either way. A line break between them costs nothing and removes the ambiguity.
if (needsValidation) {
validate(request);
} if (needsLogging) { // looks like an else if, but both run when both conditions hold
logRequest(request);
}
Remediation
Either put the two conditionals on separate lines, if they are genuinely independent, or use else if if only one of them should ever run.
if (needsValidation) {
validate(request);
}
if (needsLogging) {
logRequest(request);
}