Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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

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
bgColor#FFcccc
int i, j = 1;

...

In this compliant solution, it is readily apparent that both i and j are initialized to 1.:

Code Block
bgColor#ccccff
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
bgColor#ccccff
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
bgColor#ccccFF
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;
  }
}

...