Layout
convention: indentation
The use of indentation can be very
helpful to the human reader when statements are being used to control program
execution. Thus any statements that may never be executed (i.e. within
a selection statement), or may be executed many times (i.e. within an iteration
statement) can be indented to indicate the possible change from sequence
execution of statements.
An example of a selection statement
without indentation:
if(
accountBalance < transactionTotal ){
showMessage("sorry
no funds for transaction");
return
false;}
else
{
showMessage("transaction
processed");
accountBalance
-= transactionTotal;
return
true;}
and now written with indentation
of all statements that may or may not be executed:
if(
accountBalance < transactionTotal ){
showMessage("sorry
no funds for transaction");
return
false;}
else
{
showMessage("transaction
processed");
accountBalance
-= transactionTotal;
return
true;}
In fact with the above example, we ought
to also follow the convention for vertically aligning the braces forming
the compound statement, and so write the code as follows:
if(
accountBalance < transactionTotal )
{
showMessage("sorry no funds for transaction");
return false;
}
else
{
showMessage("transaction processed");
accountBalance -= transactionTotal;
return true;
}
This form of indentation has made this
code much easier to understand.
However, there is a danger with the
use of indentation. The use of TAB or space characters for indentation
is completely ignored by the Java compiled, thus both if statements above
are treated the same. A common programming error is to indent statements
to indicate to a human reader that the statements are part of a selection
or iteration statement, but to make an error in writing the statement so
that not all the indented statements are actually effected by the control
statement.
For example, in the following piece
of code the programmer has forgotten to use braces to create a compound
statement, so only the first indented statement is actually effected by
the control statement:
for(
int i = 0; i < balls.length; i++)
balls[i].paint( g );
balls[i].move(); // not part of loop !!
To make all the indented statements part
of this loop, braces must be added to tell the compiler where the compound
statement starts and finishes:
for(
int i = 0; i < balls.length; i++)
{
balls[i].paint( g );
balls[i].move();
}
Back
to top
RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex
University. All rights reserved.
webmaster@globalcampus.com.eg
|