Example 1:
if (DoAction())
{
result = true;
}
Example 2:
// Count number of elements in array.
for (int i = 0; i < y; i++)
{
}
Exceptions:
- an "else" statement may directly followed by another "if"
- An if clause, followed by a single statement, does not have to enclose that single statement in a block, provided that the entire statement is written on a single line.
Of course the exception is intended for those cases where it improves readability. Please note that the entire statement must be a one-liner (of reasonable length), so it is not applicable to complex conditions. Also note that the exception is only made for if (without else), not for while etc.
Examples:
if (failure) throw new InvalidOperationException("Failure!");
if (x < 10) x = 0;
Rationale for the exception: code readability can be improved because the one-liner saves vertical space (by a factor of 4). The lurking danger in later maintenance, where someone might add a statement intending it to be subject to the condition, is absent in the one-liner.
|