J2SE 1.5 Varargs - A solution looking for a problem?
I have blogged previously about inconsequential language features being added to J2SE 1.5. This particular feature plays nicely into that rant. Now, let us look at a boilerplate call using the ubiquitous example of one of the
formatmethod signatures in
java.text.MessageFormat, which creates a MessageFormat with the given pattern and uses it to format the given arguments:
public static String format(String pattern, Object arguments);
which can now be altered to
public static String format(String pattern, Object... arguments);
I will readily admit that this new representation is elegant, to say the least. API users are made aware that this method can take a variable sequence of arguments as its second parameter. That fact isn't hidden in javadocs; the signature itself speaks that out loud. In addition, the API tells you that the method isn't interested in traversing your array or manipulating it otherwise. It is only interested in the arguments you pass. So far, so good.
One can well make the case that limiting the varargs to one per method -- as is the case in 1.5 -- can be restrictive. In such cases, you would have to resort to the current practise of using an array. There is also the issue of backward compatibility or lack thereof. I do not anticipate seeing developers rushing to add support for varargs in code that has hitherto used concise object arrays. It gets worse when you think of overloaded methods that use varargs. It may not be easily apparent which method actually gets called. Sun -- to its credit -- does state this fact:
As an API designer, you should use them 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.
In that sense, the new vararg feature speaks to a very small constituency. It comes across as a solution looking for a problem. Of course, I may be missing some merits that more the experienced code cutters will recognize. I am however eager to know what they are, so please use the comment option below.
Update: I forgot to add this thread from the Java forums on "jsr 201 including varargs in public review" from Jan 25, 2004.