...
Code Block | ||
---|---|---|
| ||
int i = 1; int j = 1; |
Nomcompliant Example
In this noncompliant example, the original programmer declared multiple variables, including an array, on the same line. Since even arrays have access to all Object
methods, mistakes of this form may not be immediately detected by the compiler or an IDE.
Code Block | ||
---|---|---|
| ||
public class Example{
private T a,b,c[],d;
public Example(T in){
a = in;
b = in;
c = (T[]) new Object[10];
d = in;
} |
Thus, when it comes time to write something like the toString
method, a programmer might accidentally write it without realizing c
is an array. Since the mistake compiles cleanly, it may go undetected.
No Format |
---|
public String toString(){
return a.toString() + b.toString() + c.toString() + d.toString();
} |
However, the intended toString
might have been to invoke toString
for each T
in c
.
No Format |
---|
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
Move each declaration to a different line, so programmer error of thinking c
is a T
object, isn't as likely. Furthermore, declare arrays by putting the brackets adjacent to the type, as opposed to postfixed to the variable name.
Code Block | ||
---|---|---|
| ||
public class Example{
private T a;
private T b;
private T[] c;
private T d;
public Example(T in){
a = in;
b = in;
c = (T[]) new Object[10];
d = in;
} |
Exceptions
DCL04-01: Trivial declarations for loop counters, for example, can reasonably be included within a for
statement:
Code Block | ||
---|---|---|
| ||
for (int i = 0; i < mx; ++i ) { /* ... */ } |
Risk Assessment
Declaring no more than one variable per declaration can make code easier to read and eliminate confusion.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL04-C | low | unlikely | low | P3 | L3 |
Other Languages
This rule appears in the C Secure Coding Standard as DCL04-C. Do not declare more than one variable per declaration.
This rule appears in the C++ Secure Coding Standard as DCL04-CPP. Do not declare more than one variable per declaration.
References
Wiki Markup |
---|
\[[JLS 06|AA. Java References#JLS 06]\] Section 6.1, "Declarations" \[[JLS 06|AA. Java References#JLS 06]\] Section 4.3.2, "The class Object" |