Java Reference
In-Depth Information
follow, and you should think about whether you could move some of the indented code into a
separate method.
Spacing
Spacing is intended to make code easier to read, but too much of it can have the opposite
effect and make the code harder to read and maintain. In general, you should put one space
between a keyword and a parenthesis, after commas, between expressions in for statements,
after casts, and around all binary operators. Examples of these are shown in Table 2-3.
Table 2-3. Spacing Examples
Rule
Example
while (true)
Space between keyword and parenthesis
Space after commas
myMethod(variable1, variable2);
for (expression1; expression2; expression3) {
Space between expressions
Space after casts
int i = (int) aLongValue;
a = b + c;
c = 5 * 10;
Space after binary operators
Statement Formatting
Most of the statement-formatting rules simply follow on from the rules we have already
discussed.
Most programmers have a preferred method of writing compound statements—for
example, where to place braces, and whether braces are optional. Rather than leaving this for
endless debate, Sun has specified that braces must be used to enclose statements as part of a
control structure—even if only one statement is used in the control structure. For instance,
even if there is only one line of code to be executed following an if statement, it must still be
enclosed in braces, as shown here:
if (variable == someValue) {
doSomething();
}
As you can see, the statement between braces should be indented one indentation level
(four spaces), and the closing brace should start on its own line at the original indentation
level.
Tip Many tools are available that you can use to help you confirm that the code you have written confirms
to the Sun coding standards. One such tool is Checkstyle ( http://checkstyle.sourceforge.net/ )—it
integrates neatly into many popular IDEs, and supports many different coding styles, not just Sun's. A good
style checker will provide you with a report on what it believes needs to be changed, after which you can
manually verify each item.
Search WWH ::




Custom Search