jump to navigation

Java 5 syntax tricks to keep you DRY May 2, 2006

Posted by James Webster in : java , trackback

Update: I have changed the example a bit…

Which do you think is more readable; this…

someMethod(23, new String[]{"one", "two", "three"}, 42);

…or this…

someMethod(23, array("one", "two", "three"), 42);

The latter can be achieved in Java 5 with the following method leveraging both varargs and generics;

<T> T[] array(T... objects) {
    return objects;
}

I’m finding it useful to help maintain DRYness as the type of the array is stated once rather than twice. Of course, the array argument could be shifted to the last argument and varargs used on the method being called (if it can be implemented in Java 5). Its impossible to completely remove this sort of duplication in Java but not impossible to remove it from statically typed languages altogether. Have a look at Boo, a Python-esque language that targets .Net and Mono and supports type inference.

My examples were originally…
String[] arrayOfStrings = new String[]{"one", "two", "three"};
and
String[] arrayOfStrings = array("one", "two", "three");

As Brandon correctly identifies in the comments, the following is syntactically valid prior to Java 1.5 anyway…
String[] arrayOfStrings = {"one", "two", "three"};

Comments»

1. Brandon - May 2, 2006

Why not:

String[] arrayOfStrings = { “one”, “two”, “three” };

2. James Webster - May 2, 2006

Yeah, good point. My example was originally a bit different. I will update the post to explain what I meant.

3. Brandon - May 3, 2006

I definitely like that version better :)

Makes sense. Now, if we could only get to 1.5…

4. d. - May 3, 2006

yea cos ” T[] array(T… objects)” makes the code real clear and consise now…

5. James Webster - May 3, 2006

@d: Yes the generics syntax is a bit confusing. In my use of this technique, the array() method is living on a BaseTestCase , and usages of array() are occuring in unit tests. I like the shorthand syntax for building up arrays that are supplied to methods that I am testing.

6. Chris Munroe - May 3, 2006

you shouldn’t really use arrays, they are too primitive

7. Paul Holser - May 14, 2006

You might want to disallow zero-arg varargs lists to your method, i.e. disallow array()…in that case it’ll always return a zero-length Object array, and you’ll end up with ClassCastExceptions with constructs like:

String[] none = array();

Otherwise, great tip. Think I’ll add it to Jaggregate (http://jaggregate.sf.net).