Versions Compared

Key

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

...

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;

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;  // Purpose of i...
int j = 1;  // Purpose of j...

Compliant Solution (Initialization)

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

...

Declaring each variable on a separate line is the preferred method. However, multiple variables on one line are acceptable when they are trivial temporary variables such as array indices.

Noncompliant Code Example (Different Types)

In this noncompliant code example, the programmer declares multiple variables, including an array, on the same line. All instances of the type T have access to methods of the Object class. However, it is easy to forget that arrays require special treatment when some of these methods are overridden.

...

Code Block
// Correct functional implementation
public String toString(){
  String s = a.toString() + b.toString();
  for(int i = 0; i < c.length; i++){
    s += c[i].toString();
  }
  s += d.toString();
  return s;
}

Compliant Solution (Different Types)

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;   // Purpose of a...
  private T b;   // Purpose of b...
  private T[] c; // Purpose of c[]...
  private T d;   // Purpose of d...

  public Example(T in){
    a = in;
    b = in;
    c = (T[]) new Object[10];
    d = in;
  }
}

Applicability

Declaration of multiple variables per line can reduce code readability and lead to programmer confusion.

...

Such declarations are not required to be in a separate line; the explanatory comment may also be omitted.

Bibliography

...