Unleash the Tiger
Be it because we were too busy complaining about Java, or spending most of our free time exploring Ruby and Ruby On Rails, there has not been enough fanfare to follow the introduction of the new features that came packed with Java 1.5, such as varargs, autoboxing and static imports. And that’s a darn shame, if you ask me, as the possibilities for flexibility previously undreamt of are there to be explored.
Let’s consider the following piece of code:
package com.nutrun.tiger;
public abstract class Utility {
public static void repeat(int times, Callback callback,
Object... arguments) {
for (int i = 0; i <= times; i++) {
callback.yield(arguments);
}
}
interface Callback {
void yield(Object... arguments);
}
}
Nothing special here, except one thing: Object... arguments is of course a varargs parameter, which already makes the repeat method incredibly powerful, as the yield method in the Callback interface can take 0 to n arguments. How’s that for flexible and generic and dynamic?
Let’s look at a potential use for this, to make things a bit clearer.
import static com.nutrun.tiger.Utility.*;
public class Showcase {
public static void main(String[] args) {
repeat(3, new Callback() {
public void yield(Object ...arguments) {
for (Object argument : arguments)
System.out.println("argument = " + argument);
}
}, "rock", "metal", "blues");
}
}
Notable here is the use of the import static com.nutrun.tiger.Utility.* static import and the use of the for (Object argument : arguments) loop for extra compact code that reads nice. Not so a bad a piece of hackery, huh?
On for the home-run, then:
import static com.nutrun.tiger.Utility.*;
public class Showcase {
public static void main(String[] args) {
//...
repeat(5, new Callback() {
int number = 0;
public void yield(Object... arguments) {
for (Object argument : arguments) {
number += (Integer) argument;
System.out.println("number = " + number);
}
}
}, 3, 4, 5);
}
}
Adding a little bit of autoboxing magic to the recipe, we end up with behavior reminiscent of dynamic languages. And that’s a great win, in my opinion, as we end up with (nearly) the best of both worlds. After all, ...arguments can carry a strongly typed Collection, reinforced by Generics…
One possible drawback I notice with the code presented above is the somehow inelegant syntax. I think the possibility to support code blocks without curly braces and semi-colons would be a nice feature that I’d really like to see introduced in future releases of Java.
Could this kind of approach be what that marketing joke, Beyond Java, should have been all about?

June 20th, 2006 at 10:10 pm
If you’re doing the static import stuff (which, to me, reeks), might as well bring in a static method called proc() or something like that, which just wraps the ‘new Callback()’ call. No syntax sugar is too much!