Java Reference
In-Depth Information
Lines that are longer than 80 characters should be broken after a comma or before an
operator whenever possible. The second (and subsequent lines) should be indented to the
beginning of the expression on the previous line, or eight spaces. For example:
int i = myMethod(longNamedVariable1, longNamedVariable2,
longNamedVariable3, longNamedVariable4);
Line wrapping for if , for , and while statements generally uses the eight-space indentation
rule rather than the beginning of the expression, since using the beginning of the expression
can cause confusion with the line that follows, which will be indented four characters. The fol-
lowing example shows both the preferred and nonpreferred way of breaking if statements:
// nonpreferred way
if (myMethod(longNamedVariable1, longNamedVariable2,
longNamedVariable3, longNamedVariable4)) {
// code starts here - see how confusing this is ?
doSomething();
}
// preferred way
if (myMethod(longNamedVariable1, longNamedVariable2,
longNamedVariable3, longNamedVariable4)) {
// code starts here - now we can see the difference between
// the condition and the code to be run within the condition
doSomething();
}
In cases where you have multiple levels of code in one line, for example, calling a method and
using the result as a parameter to another method call, it is preferable to break the line at the
higher level—keep the call to the external method on one line where possible. For example:
int i = myMethod(variable1,
callToAnotherMethod(variable1, variable2),
(variable1 + variable2));
In such cases as this last example, you should consider whether your code would be more
readable and understandable if you were to refactor it. For example, you could
Move the external procedure call to a separate line.
Move the calculation in parentheses to a separate line.
Make both modifications.
Consider how much easier the following code might be to read and maintain:
int dbValue = callToAnotherMethod(variable1, variable2);
int calculated = variable1 + variable2;
int i = myMethod(variable1, dbValue, calculated);
Once you get beyond your third or fourth level of indentation, you may find that these
rules are hard to follow. This is often also an indication that your code may be difficult to
Search WWH ::




Custom Search