Versions Compared

Key

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

...

Wiki Markup
As an API designer, you should use \[varargs methods\] sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called. 

Noncompliant Code Example

Overloading varargs methods can create confusion as shown in this noncompliant code example. The programmer's intent is to invoke the variable argument (varargs) doSomething() method, but instead its overloaded, more specific form takes precedence.

Code Block
bgColor#FFCCCC
class OverloadedVarargs {
  private static void doSomething(boolean... bool) {
    System.out.print("Number of arguments: " + bool.length + ", Contents: ");

    for (boolean b : bool)
      System.out.print("[" + b + "]");
  } 
  private static void doSomething(boolean bool1, boolean bool2) {
    System.out.println("Overloaded method invoked");  
  }
  public static void main(String[] args) {
    doSomething(true, false);
  }
}

Compliant Solution

Avoid overloading varargs methods. Use distinct method names so that the intended method gets invoked as prescribed by this compliant solution.

Code Block
bgColor#ccccff
class NotOverloadedVarargs {
  private static void doSomething1(boolean... bool) {
    System.out.print("Number of arguments: " + bool.length + ", Contents: ");

    for (boolean b : bool)
      System.out.print("[" + b + "]");
  } 
  private static void doSomething2(boolean bool1, boolean bool2) {
    System.out.println("Overloaded method invoked");  
  }
  public static void main(String[] args) {
    doSomething1(true, false);
  }
}

Exceptions

Wiki Markup
*DCL08-EX1:* Sometimes, it is desirable to violate the "do not overload varargs methods" advice for performance reasons (avoiding the cost of creation of an array instance and its initialization on every invocation of a varargs method). \[[Bloch 2008|AA. Bibliography#Bloch 08]\]

...

The idiom shown above avoids the pitfalls of incorrect method selection by using non-ambiguous method signatures and can be discreetly used where required.

Risk Assessment

Unmindful use of the varargs feature may create ambiguity and diminish code readability.

Guideline

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 guideline on the CERT website.

Bibliography

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

...