Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Changed to JG, and changed some text

The Java compiler type-checks the arguments to each varargs method to ensure that the arguments are of the same type or object reference. However, the compile-time checking is ineffective when Object or generic T parameter types are used [Bloch 2008]. 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 (Object)

This noncompliant code example declares a vararg method using Object. It accepts an arbitrary mix of parameters of any object type. Legitimate uses of such declarations are rare. (See "Exceptions").

Code Block
bgColor#FFCCCC

ReturnType method(Object... args) { }

Noncompliant Code Example (Generic Type)

This noncompliant code example declares a vararg method using a generic type parameter. It accepts a variable number of parameters that are all of the same object type. Again, legitimate uses of such declarations are rare.

Code Block
bgColor#FFCCCC

<T> ReturnType method(T... args) { }

Compliant Solution

Be as specific as possible when declaring parameter types; avoid Object and imprecise generic types in varargs.

Code Block
bgColor#ccccff

ReturnType method(SpecificObjectType... args) { }

...

Also, note that autoboxing does not allow strong compile-time type checking of primitive types and their corresponding wrapper classes.

Exceptions

DCL03DCL60-EX0: Varargs signatures using Object and imprecise generic types are acceptable when the body of the method does not use casts or autoboxing and compiles without error. Consider the following example, which operates correctly for all object types and type-checks successfully.

Code Block
bgColor#ccccff

Collection<T> assembleCollection(T... args) {
  Collection<T> result = new HashSet<T>();
  // add each argument to the result collection
  return result;
}

Risk Assessment

Unmindful Injudicious use of the varargs feature parameter types prevents strong compile-time type checking, creates ambiguity, and diminishes code readability.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL03DCL60-J JG

low

unlikely

medium

P2

L3

Automated Detection

Automated detection appears to be straightforward.

Bibliography

[Bloch 2008]

Item 42: "Use Varargs Judiciously"

[Steinberg 2005]

"Using the Varargs Language Feature"

[Sun 2006]

varargs

 

DCL59-JG. Avoid ambiguous overloading of varargs methods      01. Declarations and Initialization (DCL)      DCL58-JG. Do not derive a value associated with an enum from its ordinal