A variable arity (aka varargs) method is a method that can take a variable number of arguments. The method must contain at least one fixed argument. When processing a variable arity method call, 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 types of all arguments, and all of the variable actual arguments must match the variable formal argument type. However, compile-time type checking is ineffective when Object
or generic T
parameter types are used [Bloch 2008]. Another requirement for providing The presence of initial parameters of specific types is irrelevant; the compiler will remain unable to check Object
or generic variable parameter types. Enable strong compile-time type checking of variable argument methods is to be as specific as possible when declaring the type of arity methods by using the most specific type possible for the method parameter.
Noncompliant Code Example (Object
)
This noncompliant code example declares a vararg method using Object
. It sums a set of numbers using a variable arity method that uses Object
as the variable arity type. Consequently, this method accepts an arbitrary mix of parameters of any object type. Legitimate uses of such declarations are rare . (See but see the "ExceptionsApplicability" section of this guideline).
Code Block | ||
---|---|---|
| ||
double sum(Object... args) {
double result = 0.0;
for (Object arg : args) {
if (arg instanceof Byte) {
result += ((Byte) arg).byteValue();
} else if (arg instanceof Short) {
result += ((Short) arg).shortValue();
} else if (arg instanceof Integer) {
result += ((Integer) arg).intValue();
} else if (arg instanceof Long) {
result += ((Long) arg).longValue();
} else if (arg instanceof Float) {
result += ((Float) arg).floatValue();
} else if (arg instanceof Double) {
result += ((Double) arg).doubleValue();
} else {
throw new ClassCastException();
}
}
return result;
} |
Compliant Solution (Number
)
This compliant solution defines the same method but uses the Number
type. This abstract class is general enough to encompass all numeric types, yet specific enough to exclude nonnumeric types.
Code Block | ||
---|---|---|
| ||
double sum(Number ReturnType method(Object... args) { // ... } |
Noncompliant Code Example (Generic Type)
This noncompliant code example declares a vararg the same variable arity method using a generic type parameter. It accepts a variable number of parameters that are all of the same object type; however, it may be any object type. Again, legitimate uses of such declarations are rare.
Code Block | ||
---|---|---|
| ||
<T> ReturnTypedouble methodsum(T... args) { } // ... } |
Compliant Solution
...
(Generic Type)
This compliant solution defines the same generic method using the Number
typeBe as specific as possible when declaring parameter types; avoid Object
and imprecise generic types in varargs.
Code Block | ||
---|---|---|
| ||
ReturnType method(SpecificObjectType<T extends Number> double sum(T... args) { // ... } |
Be as specific as possible when declaring parameter types; avoid Object
and imprecise generic types in variable arity methods. Retrofitting Retrofitting old methods containing final array parameters with generically typed varargs variable arity parameters is not always a good idea. For example, given a method that does not accept an argument of a particular type, it could be possible to override the compile-time checking — through checking—through the use of generic varargs parameters — so variable arity parameters—so that the method would compile cleanly rather than correctly, causing a compile-time runtime error [Bloch 2008].
Also, note that autoboxing does not allow prevents strong compile-time type checking of primitive types and their corresponding wrapper classes. For instance, this compliant solution produces the following warning but works as expected:
Java.java:10: warning: [unchecked] Possible heap pollution from parameterized vararg type T
<T extends Number> double sum(T... args) {
Exceptions
Applicability
Injudicious use of variable arity parameter types prevents strong compile-time type checking, creates ambiguity, and diminishes code readability.
Variable arity DCL03-EX0: Varargs signatures using Object
and imprecise generic types are acceptable when the body of the method does not use casts or lacks both casts and autoboxing and it also compiles without error. Consider the following example, which operates correctly for all object types and type-checks successfully. :
Code Block | ||
---|---|---|
| ||
<T> Collection<T> assembleCollection(T... args) { Collection<T> result =return new HashSet<T>(Arrays.asList( args)); // add each argument to the result collection return result; } |
Risk Assessment
Unmindful use of the varargs feature prevents strong compile-time type checking, creates ambiguity, and diminishes code readability.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL03-J | low | unlikely | medium | P2 | L3 |
Automated Detection
In some circumstances, it is necessary to use a variable arity parameter of type Object
. A good example is the method java.util.Formatter.format(String format, Object... args)
, which can format objects of any type.
Automated detection is Automated detection appears to be straightforward.
Bibliography
Item 42: , "Use Varargs Judiciously" | ||
"Using the Varargs Language Feature" | ||
...
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