Sunday, 20 September 2009

Item 27: Favour Generic Methods

Basically, in this item Joshua is telling us that as well as using generic types, we should make our methods generic too. So instead of:

public static Set union(Set s1, Set s2)
{
Set result = new HashSet(s1);
result.addAll(s2);
return result;
}

We should use generics:

public static <E> union(Set<E> s1, Set<E> s2)
{
Set<E> result = new HashSet<E>(s1);
result.addAll(s2);
return result;
}

because the later example provides us with type safety. The compiler uses type inference to work out the return type. All very straight forward and makes complete sense. Joshua could have left it there, but he goes on to show how we could write factory method that enables us to create a generic type and only specify the generic parameters on one side of the expression:

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

HashMap<K,V> anagrams = new HashMap();

Even as a C++ programmer who desperately misses typedef, I can't see myself doing this. Just think how many of these static functions you'd need to write to handle all the constructor variations for each type.

Joshua continues with two other examples, but I think the point is well and truly driven home by now. Use generic functions to compliment your generic types. Less code, more software.

Paul Grenyer

No comments: