Versions Compared

Key

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

...

Another requirement for providing strong compile-time type checking of variable argument methods is to be as specific as possible when declaring the type of the method parameter.

Noncompliant Code Example

This noncompliant code example declares two methods, one with an Object parameter and another with a generic type T. Both these approaches are flawed as they break string compile-time type checking.

Code Block
bgColor#FFCCCC
ReturnType1 suspect1(Object... args) { }
<T> ReturnType2 suspect2(T... args) { }

Compliant Solution

Do not use generic types like Object in varargs and be as specific as possible when declaring parameter types.

Code Block
bgColor#ccccff
ReturnType1 specific1(primitiveType1... args) { }
ReturnType2 specific2(primitiveType2... args) { }

Noncompliant Code Example

This noncompliant code example shows autoboxing in action when the doSomething method is called with the primitive integer 1 as a parameter (converted to Integer type).

Code Block
bgColor#FFCCCC
doSomething(1)

private void doSomething(Integer... i) {
  System.out.println("autoboxed");
}

Compliant Solution

Be as specific as possible while defining the type of a varargs method to enforce strong compile-time checking.

Code Block
bgColor#ccccff
doSomething(1)

private void doSomething(int... i) { // use int instead of Integer here
  System.out.println("specific");
}

Risk Assessment

Unmindful use of the varargs feature breaks strong compile-time type checking, may create ambiguity and diminish code readability.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL08-J

low

unlikely

medium

P2

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[Sun 06|AA. Java References#Sun 06]\] [varargs|http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html] 
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 42: "Use varargs judiciously"
\[[Steinberg 05|AA. Java References#Steinberg 05]\] "Using the Varargs Language Feature"

...