Hi,
I have a question regarding the usage of variable arguments (VarArgs).
I am developing a framework and several of the classes in this
framework allow the developer to 'add' objects to them. One way of
implementing this is by passing a collection, an array, or a variable
argument. Is there a best practise on how to implement this?
Example:
Option 1: addMyObjects(Collection<MyObject> objects);
Option 2: addMyObjects(MyObject[] objects);
Option 3: addMyObjects(MyObject... objects);
I like option 3 because this way the developer can pass a single
object very easily without the need of creating an array.
Your thoughts?
--Dirk
Roedy Green - 22 Aug 2007 12:39 GMT
>I like option 3 because this way the developer can pass a single
>object very easily without the need of creating an array.
>
>Your thoughts?
Have a look at how EnumSet works. They have dozens of overloaded
methods. They have one, two, three parms, varargs, collection ...
To the user, you can throw anything reasonable at it.

Signature
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Daniel Pitts - 22 Aug 2007 22:25 GMT
> Hi,
>
[quoted text clipped - 18 lines]
>
> --Dirk
I would prefer Collection<MyObject> personally. using [] or ... is
the primative obsession codesmell (Refactory p.81, Fowler, 2006)
Daniel Dyer - 22 Aug 2007 23:11 GMT
> Hi,
>
[quoted text clipped - 14 lines]
> I like option 3 because this way the developer can pass a single
> object very easily without the need of creating an array.
I would usually prefer the first approach (either Collection<MyObject>,
List<MyObject> or Set<MyObject> as appropriate).
The varargs approach is OK as long as you aren't using generics. This
situation is a special case of "generics and arrays don't mix". Consider
the method:
addMyObjects(MyObject<E>... objects)
Nothing wrong with that declaration. The problem comes when you try to
invoke the method. Invocations will generate a compile-time warning about
(implicit) "generic array creation". Of course, you can suppress the
warnings but you have to do that in every place that the method is invoked.
Dan.

Signature
Daniel Dyer
http://www.uncommons.org