Guideline IF3: Keep if-then-else statements structured
Compound statements and statement blocks. A compound statement is simply more than one statement enclosed in a bracket of some type. As it happens, many computer languages, by design or by happenstance, use the same notation:
{ statement1; statement2; statement3; }
The definition of a statement in many languages is "either a simple-statement or a compound-statement". A compound-statement is further defined as "an opening bracket, a series of statements, and a closing bracket". So the definition is recursive. Generally, then, you can use a compound statement wherever you can use a simple statement.
if (condition) x = 3; if (condition) { x = 3; y = 4; z= 5; }
Java and JavaScript useif (condition) statement
while Perl usesif (condition) block
In Perl, however, the above doesn't work, because of the definition of a statement. (Ignoring the fact that Perl also needs the dollar sign ($) prefix on variables, of course.)
A block is identical to a compound-statement as we've defined it above; the distinction in Perl is that the brackets are required in the if
statement even if there is only a single statement following the condition.
In Perl this holds true for loops as well as conditionals.
At first glance I didn't think too much about that rather elementary detail of the language syntax, but I came to realize that it is clearly a guideline for the clean code repertoire in other languages. Consider the following example.
if (cond1) statement1a; statement1b; else if (cond2) statement2a; statement2b; else if (cond3) statement2a; statement2b;
What is wrong with that code? We execute statements 1a and 1b if cond1 is true, statements 2a and 2b if cond2 is true... or do we? Remember the compiler or interpreter does not care about indentation--it only "reads" what you wrote. Did you notice the missing braces? The code should be written:
if (cond1) { statement1a; statement1b; } else if (cond2) { statement2a; statement2b; } else if (cond3) { statement2a; statement2b; }
Again, Perl would require the braces in a similar chunk of code; Java and JavaScript do not. I have found one resource, however, a code verifier for JavaScript called jslint which does require such blocks rather than compound-statements.
Just one more thing... Recall our preferred if
statement syntax is
if (condition) block
.
Note that Java, JavaScript, and Perl (and many others) do require the parentheses around the condition
; life would be a lot more difficult without that...