Page 335 - Introduction to Programming with Java: A Problem Solving Approach
P. 335

                There is one exception to the first rule:
Code that follows a switch statement’s case clause is considered to be logically inside the case clause, but braces are not used.
Variable Declarations
As shown in Figure 8.1’s main method, place all local variable declarations at the top of the method (even though that’s not required by the compiler). Exception: Unless you need a for loop iteration variable to per- sist beyond the end of the for loop, declare it in the initialization field of the for loop header.
Normally, specify only one variable declaration per line. Exception: If several variables with obvious meanings are intimately related, it’s OK to group them on one line.
Include a comment for every variable whose meaning is not obvious. For example, the cryptic local variable declarations in the main method in Figure 8.1 definitely need comments, and we also provide com- ments for the instance-variable declarations in Figure 8.2a. Note how those comments are aligned—their //’s are in the same column. In general, if you have comments that appear at the right side of several nearby lines, try to align those comments.
Line Wrap
If you have a statement that is too long to fit on one line, split it at one or more natural breaking points within the statement. For example, note where we break the long print statement in Figure 8.2b’s setFirst and setLast methods. We consider these to be natural breaking points:
• right after the openingAppareanthgesois PDF Enhancer • afteraconcatenationoperator
• afteracommathatseparatesparameters
• at whitespace in expressions
After a break point in a long statement, indent the remaining part of the statement on the next line. In Figure 8.2b, note how we indented the continuation lines with the same standard two-space width that we use for all other indentations.
Rather than simply indenting continuation lines with the standard indentation width, some program- mers prefer to align continuation lines with a parallel entity on the previous line. For example, in the afore- mentioned print statement, they would align the continuation line with first like this:
System.out.println(first +
" is an invalid name.\n" +
" Names must start with an uppercase" +
" letter and have lowercase letters" +
" thereafter.");
In our opinion, the above code is pushed too far to the right and is unnecessarily chopped up. That’s why we prefer to keep it simple and just indent with the normal indentation width.
Braces That Surround One Statement
For a loop statement or an if statement that includes only one subordinate, it’s legal to omit the braces around the statement. For example, in Figure 8.2b’s setFirst method, the if-else statement could be writ- ten like this:
8.2 Coding-Style Conventions 301













































































   333   334   335   336   337