19.2. Compound Statements (Blocks)

 < Free Open Study > 

A "compound statement" or "block" is a collection of statements that are treated as a single statement for purposes of controlling the flow of a program. Compound statements are created by writing { and } around a group of statements in C++, C#, C, and Java. Sometimes they are implied by the keywords of a command, such as For and Next in Visual Basic. Guidelines for using compound statements effectively follow:

Write pairs of braces together Fill in the middle after you write both the opening and closing parts of a block. People often complain about how hard it is to match pairs of braces or begin-and-end pairs, and that's a completely unnecessary problem. If you follow this guideline, you will never have trouble matching such pairs again.

Cross-Reference

Many programmer-oriented text editors have commands that match braces, brackets, and parentheses. For details, see "Editing" in Section 30.2.


Write this first:

for ( i = 0; i < maxLines; i++ )

Write this next:

for ( i = 0; i < maxLines; i++ ) { }

Write this last:

for ( i = 0; i < maxLines; i++ ) {    // whatever goes in here ... }

This applies to all blocking structures, including if, for, and while in C++ and Java and the If-Then-Else, For-Next, and While-Wend combinations in Visual Basic.

Use braces to clarify conditionals Conditionals are hard enough to read without having to determine which statements go with the if test. Putting a single statement after an if test is sometimes appealing aesthetically, but under maintenance such statements tend to become more complicated blocks, and single statements are errorprone when that happens.

Use blocks to clarify your intentions regardless of whether the code inside the block is 1 line or 20.

 < Free Open Study > 


Code Complete
Code Complete: A Practical Handbook of Software Construction, Second Edition
ISBN: 0735619670
EAN: 2147483647
Year: 2003
Pages: 334

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net