Java Reference
In-Depth Information
Conventions for indentation
Indentation is used to help expose the structure of a program. A program that is
not well indented can be hard to read because its structure may not be apparent.
Watch ProgramLive 's activity 13-3.1 to see how hard it is to read a program that
is badly indented. Also, activity 12-3.2 discusses two issues to watch out for
when indenting.
Indentation conventions are based on two simple principles:
1. In a sequence of constructs —variable declarations, method definitions, state-
ments, and the like— all the constructs are indented the same amount.
2. If a Java construct requires more than one line, its subconstructs that appear
after the first line are indented.
Beyond these two principles, a few extra conventions are used to deal with
the use of braces { and } to aggregate statements into a single statement. There
are several ways to do this, and we comment briefly on them in the following
In this text, we generally indent by four blanks at a time. Your IDE probably
has a preference panel where you can define how many spaces a tab indents.
Indenting if-statements
We put the opening brace of the then-part on the same line as the if-condition and
put the closing brace on a separate line, indented the same as the if :
See lesson
page 13-3.
if (...) {
This convention is used because placing the opening brace on a line by itself
takes another line, and the number of lines on the monitor is a scarce resource.
We (almost) always use a block for the then-part, even if it contains a single
statement. This convention prevents us from writing an if statement:
if (...)
and then later adding another statement and assuming that it is part of the then-
part, which it is not :
if (...)
If the then-part is one line, we sometimes write it like this:
Search WWH ::

Custom Search