Handy Convenience Methods with Varargs and Generic Methods

When I’m dealing with code that uses collections or arrays, I often find myself writing these convenience methods. This is especially true within unit tests, where reducing SnR is very important.

The first one is for creating an empty list, set, or map etc without having to duplicate the template parameters. Here it’s written for a HashMap:

private static <K, V> Map<K, V> newHashMap() {
    return new HashMap<K, V>();
}

It can be used as follows:

// would have had to write
// private final Map<UserId, Set<PhoneNumber>> _phByUserId = 
//       new HashMap<UserId, Set<PhoneNumber>>();
// instead we can simplify to
private final Map<UserId, Set<PhoneNumber>> _phByUserId = newHashMap();

The next method is used to instantiate and populate a list or a set:

private static <T> Set<T> toHashSet(T... elements) {
    Set set = new HashSet<T>();
    for (T element : elements) {
        set.add(element);
    }
    return set;
}

The varargs lend the method to elegant use:

Set<String> resourceNames = 
    toHashSet(
      "simple_request.xml",
      "malformed_request.xml",
      "incomplete_request.xml"
    );

A similar method can be written for instantiating pre-populated lists. If you know that the list will never be added to, you can forgo writing any convenience method, and use java.util.Arrays directly:

import static java.util.Arrays.asList;
...
List<String> resourceNames =
    asList(
      "simple_request.xml",
      "malformed_request.xml",
      "incomplete_request.xml"
    );

The last also happens to be my favorite. Instantiating pre-populated arrays in Java involves far too much typing. For example:

Class[] interfaces = new Class[] { Person.class, Customer.class };

Using the following simple convenience…

private static <T> T[] array(T... elements) {
    return elements;
}

… The earlier expression can be replaced with:

Class[] interfaces = array(Person.class, Customer.class);
Post a comment or leave a trackback: Trackback URL.

Leave a comment