...
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§6.1, "Number Per Line" [Conventions 2009].
This guideline applies to
- local Local variable declaration statements [Java 2011, §14.4],
- field Field declarations [Java 2011, §8.3],
- field Field (constant) declarations [Java 2011, §9.3],
Noncompliant Code Example (Initialization)
This noncompliant code example might lead a programmer or reviewer to mistakenly believe that both i
and j
are initialized to 1. In fact, only j
is initialized; i
remains uninitialized.:
Code Block | ||
---|---|---|
| ||
int i, j = 1; |
...
In this compliant solution, it is readily apparent that both i
and j
are initialized to 1.:
Code Block | ||
---|---|---|
| ||
int i = 1; // purposePurpose of i... int j = 1; // purposePurpose of j... |
Compliant Solution (Initialization)
In this compliant solution, it is readily apparent that both i
and j
are initialized to 1.:
Code Block | ||
---|---|---|
| ||
int i = 1, j = 1; |
...
This compliant solution places each declaration on its own line and uses the preferred notation for array declaration.:
Code Block | ||
---|---|---|
| ||
public class Example { private T a; // purposePurpose of a... private T b; // purposePurpose of b... private T[] c; // purposePurpose of c[]... private T d; // purposePurpose of d... public Example(T in){ a = in; b = in; c = (T[]) new Object[10]; d = in; } } |
...