I'm implementing an API an have a method which you pass a list of paths where the program reads resources from
public void importFrom(String... paths) {
}
I'm using varargs to make calling the method as convenient as possible to the user, like so
obj.importFrom("/foo", "/foo/bar);
Is this an appropriate use of varargs? Or is passing in an array better?
Since varargs arguments get compiled into a single array argument you could generally prefer varargs since this might be more convinient in some cases and still allows to pass an array in other cases.
compiles into
Alternatively you could also use
Iterable<String>
to make it easier to pass the arguments as collection.In your case varargs is just fine. You don't really need to make an array of the paths that you will be importing because there's nothing you want to do with these paths other than to pass them along to your
importFrom
method.The varargs functionality saves you from having to explicitly create an array solely for the purpose of passing a collection of values to a one-off method, which you do appear to have here.
BTW, you can still pass in an array if you want to
Because the behavior is the same, the difference comes down to a (probably minor) question of what you want the method signature to "say". When you declare a method to take an explicit array parameter, it's almost as if you want to stress that you want to operate on an array object, something that has been defined outside the method and has its own existence and importance outside the method, and one in which, perhaps, operations like indexing matter. When declaring the method with varargs, its as if you are saying "just give me a bunch of items".
Then again, this doesn't have to be true; the JVM doesn't know the difference, all it sees is an array at run time. Many programmers won't bother splitting hairs over the intent of the method signature. Varargs is all about making the calls convenient.
That said, the main limitation of varargs is that such a parameter must be the last one of the method. In your case this is not a problem, but in general it is something to consider.
I think the other alternative is to use
List<String>
. Personally I would use aList
if there are more than a few arguments or if arguments are automatically processed from somewhere (parsed from a file for example).If you will be writing the arguments manually in the code, then I would prefer using the varargs as you proposed.
The answer depends on the intended use of your function. If the user typically knows at coding time which arguments he wants to pass in,
varargs
is the way to go. If the user needs to be able to determine the number of arguments at runtime, an array argument will make life a lot easier for him (or her).