...
More important, it is easy to forget to add braces when inserting additional statements into a body containing only a single statement, because the conventional indentation gives strong (but misleading) guidance to the structure.
...
Code Block | ||
---|---|---|
| ||
int login; if (invalid_login()) login = 0; else login = 1; |
A This program behaves as expected. However, a maintainer might subsequently add a debug statement or other logic but forget to add opening and closing braces:
Code Block | ||
---|---|---|
| ||
int login; if (invalid_login()) login = 0; else // Debug line added belov System.out.println("Login is valid\n"); // DebuggingThe next line is addedalways executed here login login = 1; // This line always gets executed regardless of a valid login! |
The code's indentation disguises the functionality of the program, potentially leading to a security breach.
...
This compliant solution uses opening and closing braces even though the body of the if
and else
bodies of the if is a statement are single statementstatements:
Code Block | ||
---|---|---|
| ||
int login; if (invalid_login()) { login = 0; } else { login = 1; } |
...
This noncompliant code example nests an if
statement within another if
statement, without braces around the if
and else
bodies:
...
The indentation might lead the programmer to believe users are granted administrator privileges only when their login is valid. However, the else
statement actually attaches binds to the inner if
statement:
Code Block | ||
---|---|---|
| ||
int privileges; if (invalid_login()) if (allow_guests()) privileges = GUEST; else privileges = ADMINISTRATOR; |
...
Failure to enclose the bodies of if
, for
, or while
statements in braces makes code maintenance error prone and increases maintenance costs.
Bibliography
...