Sunday, May 18, 2008

How do You Use Generics in Java?

Cedric has fired up some more flames in the never-ending dynamic vs. static language wars. I won't bother with all of the obviously flammable objects in that post, but instead with this quote that I found really surprising:
90% of the Java programmers (including myself) only ever use Generics for Collections.

Is this true? It's not for me, obviously or I wouldn't have been surprised by it. Generics are so useful beyond collections. One of the most commonly implemented interfaces I deal with looks like:

interface Service<R,S> {
   S processRequest(R request);
}

This is a very simple use of generics to add type safety to a common construct. What would this look like without generics? Either everything is an Object, or there are some wrapper interfaces that would have some kind of getData() method that returns ... an Object. It's not type safe but nothing else could be reusable. 

A lot of people think that Java took a wicked turn with the 1.5 release, and generics are probably the biggest reason for this. To me, the key was if you had programmed in C++ before or not. If you had, then generics seemed natural. It was definitely not the same as C++ templates, but the concepts were similar and the syntax very similar. If you had not experienced C++ templates, then generics were terrifying. I would guess that camp probably would agree with Cedric's post, i.e. they only use them for collections.

Of course the next great scary Java feature is closures. The BGGA proposal leverages generics to specify checked Exceptions, such as below:

public static <T,throws E extends Exception>
T withLock(Lock lock, {=>T throws E} block) throws E { ... }

Even scarier? Maybe so... Anyways, I am genuinely curious how other folks use generics. Is it just for collections?

No comments: