...
In general, you should declare each variable on its own line with an explanatory comment regarding its role. Although it is not required for conformance with this guideline, this practice is also recommended in the Code Conventions for the Java Programming Language, Section 6.1, "Number Per Line" [Conventions 2009].
When more than one variable is declared in a single declaration, ensure that both the type and the initial value of each variable are self-evident.
This guideline applies to
- local variable declaration statements [Java 20052011, §14.4]
- field declarations [Java 20052011, §8.3]
- field (constant) declarations [Java 20052011, §9.3]
Noncompliant Code Example (Initialization)
...
Declaration of multiple variables per line can reduce code readability and lead to programmer confusion.
When more than one variable is declared in a single declaration, ensure that both the type and the initial value of each variable are self-evident.
Declarations of loop indices should be included within a for
statement (although this, technically, violates Note that the declaration of a loop counter in a for
statement is in violation of this guideline because the declaration is not on its own line with an explanatory comment about the variable's role. However, declaration of loop indices in for
statements is not only a common idiom but also provides the benefit of restricting the scope of the loop index to the for
loop itself. This is a specific reason to relax this guideline.Declarations of loop indices should be included within a for
statement):
Code Block | ||
---|---|---|
| ||
public class Example { void function() { int mx = 100; // some max value for (int i = 0; i < mx; ++i ) { /* ... */ } } } |
...
Section 6.1, "Number Per Line" | |
[ESA 2005] | Rule 9: Put single variable definitions in separate lines. |
| |
| |
| |
|