Saturday, July 29, 2006

A Java trick with varargs to enforce argument count

Perhaps you've seen this before, but it is new to me:

public void doSomethingAmazing(
        final String firstArgument,
        final String... restOfArguments) {
    // Do something amazing with the arguments

What is the point of firstOne and restOfThem (besides looking a little LISPy)?

Fortunately, the coder had this comment for the method: Change from checking at runtime for one or more arguments to syntatically enforcing a mandatory first argument and optional list of remaining arguments. A quick check showed the previous version as:

public void doSomethingAmazing(
        final String... arguments) {
    // Do something amazing with the arguments

Aha, how clever! Whereas before the call:


compiled but at runtime threw an IllegalArgumentException for empty arguments[], now the same call is a syntax error caught by the compiler. The correct new call is:


I like it.

UPDATE: Paul Holser points out to me that he uses this trick in the excellent JAggregate. As I reviewed that code within the past several months, I now realize that it is most likely I had already seen this trick there first. Paul is a clever guy, and deserves the credit.

Post a Comment