Control Structures Should Use Curly Braces
What is it?
This practice is triggered when control structures such as if
, for
, or while
statements in Java do not use curly braces for their body.
Why apply it?
Omitting curly braces can lead to code that is misleading and error-prone during maintenance. Using curly braces improves readability and ensures that control structures only affect the intended statements.
How to fix it?
Always include curly braces with control structures to clearly define the code block they affect.
Examples
Example 1:
Negative
The negative example omits curly braces, which can lead to confusion about which statements are inside the control structure.
for (int i = 0; i < 5; i++)
if (i % 2 == 0)
System.out.println("Even number: " + i);
continueProcessing(); // This will always be executed.
Example 2:
Positive
The positive example uses curly braces for the if
statement and for
loop, ensuring clear block definitions.
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) {
System.out.println("Even number: " + i);
continueProcessing();
}
}
Negative
The negative example omits curly braces for the while
loop, making it appear as if multiple statements are part of the loop body, when only the first one is.
int i = 0;
while (i < 5)
if (checkCondition(i))
performAction(i);
i++; // This will run independently of the condition.
Example 3:
Positive
The positive example uses curly braces with the while
loop, clearly defining the statements within the loop body.
int i = 0;
while (i < 5) {
if (checkCondition(i)) {
performAction(i);
i++;
}
}