Tuesday, December 30, 2003

Variable-length argument lists

The varargs mechanism in C/C++ is a useful but error prone approach for supporting variable-length argument lists. The main problem with varargs is that the called function needs to figure out, somehow, how many arguments were passed. Some functions such as printf do this by using a format string to determine the type and number of arguments passed in. Like many things in C/C++, this isn't type-safe and can cause problems if the caller doesn't pass the proper number or type of arguments as specified in the format string.

Java 1.4 and earlier don't support variable-length argument lists. The usual work-around is to define multiple methods that take an increasing number of arguments. For example:
public void log(String arg);
public void log(String arg1, String arg2);
public void log(String arg1, String arg2, String arg3);
A couple of less-attractive alternatives are to use an array or Properties argument to collect the arguments.

C# allows variable argument lists via the params keyword. Java 1.5 will have support for the variable argument lists using the <type-name>... syntax. In both cases the variable length argument is effectively of a single type (e.g. String or Object). Not quite as flexible as varargs but this approach is typesafe and the called method can easily determine how many arguments were passed in.

Note: JSR 65: Concise Object-Array Literals had an interesting proposal for creating array literals by automatically boxing other literal types (e.g. int, double, ...). The proposal was withdrawn. Java 1.5 will support automatic box/unbox of primitive types. I wonder if automatic boxing of other literals in Object array literals will "just work" in Java 1.5?