Use opening and closing braces for if
, for
, or while
statements even when the body contains only a single statement. Braces improve the uniformity and readability of code.
More importantlyimportant, it is easy to forget to add braces when inserting additional statements into a body containing only a single statement, because the indentation gives strong (but misleading) guidance to the structure.
...
Code Block | ||
---|---|---|
| ||
int login; if (invalid_login()) login = 0; else System.out.println("Login is valid\n"); // debuggingDebugging line added here login = 1; // thisThis line always gets executed regardless of a valid login! |
...
This compliant solution uses opening and closing braces even though the body of the if
is a single statement.
Code Block | ||
---|---|---|
| ||
int login; if (invalid_login()) { login = 0; } else { login = 1; } |
...
Related Guidelines
[Rogue 2000] | Rule 76: , Use block statements instead of expression statements in control flow constructs |
...
...