Versions Compared

Key

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

...

As an API designer, you should use [variable arity 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

In this noncompliant code example, overloading variable arity methods makes it unclear which definition of the displayBooleans() method is invoked:

...

because the nonvariable arity definition is more specific and consequently a better fit for the arguments given. However, this complexity is best avoided.

Compliant Solution

To avoid overloading variable arity methods, use distinct method names to ensure that the intended method is invoked, as shown in this compliant solution:

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

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

Applicability

Injudicious use of overloaded variable arity methods may create ambiguity and diminish code readability.

...

Automated detection is straightforward.

Bibliography

[Bloch 2008]

Item 42, "Use Varargs Judiciously"

[Steinberg 2005]

"Using the Varargs Language Feature"

[Sun 2006]

varargs

...