Wednesday, April 30, 2008

variable arguments in java

I have to confess that I totally missed out on Varargs in Java. This is embarrasing. Yesterday I have been searching for a method in Sesame (www.openrdf.org) that takes (among others) 3 Resource instances as parameters. I could not find it although the code compiled and I did call it. Guess why ;-).

I don't think it's a good idea to use that Java 5! language feature. It can lead to poor traceability and to error-prone code. Instead I would always use collections. What do you think?

Here's an example in case someone else missed out on it too:


public class VarargTest {

public static void func(String p1, String... args) {
for(String arg : args) System.out.println(arg);
}

public static void main(String args[]) {
func("a");
func("a","b");
func("a","b","c");
}
}

1 comment:

Gert Kropiunik said...

I don’t see the big benefit either. Another example where this can be really confusing is method overloading.

public void doit(String foo, Object… bar) {…. // do something }
public void doit(String foo, String bar) {…. //do something else }

So how can I call the first method with two String arguments?

doit(“foo”, “bar”); //calls the second
doit(“foo”, (Object) “bar”); //calls the first
doit(“foo”, “bar”, “foo”); //calls the first