Generics in Java are awful

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at:

I am not much of a Java hacker, so take this with a grain of salt, but I hate generics, and I think their syntax is unbelievably ugly. I am pleased to see someone with more credibility than myself, Eric Armstrong, agrees with me:

The result is a two-fold loss–a loss of both elegance and readability–that to my mind is nothing short of a travesty. It represents the virtual destruction of a good language at the hands of something that undoubtedly seemed like a good idea at the time.

When I look at code I’ve written using generics, and mentally strip out the generic portions, I can’t say that the code is any better or worse than it was before. Generics just don’t seem to be adding any real value.

Of course, generics create greater “type safety” at compile time. And that, I think, is the ultimate condemnation of static type checking: They show how much work you really have to do to get it. And what is your return for that investment? Not much, really. You get a small percentage increase in the number of real errors found at compile-time.

But to get that marginal increase, you spend more time adding required syntax, watching the compiler find silly omissions and typos, and making changes solely to satisfy the compiler. In return, you get code that is less readable.

If all that work produced code that was truly bulletproof, it could easily be worth the investment of effort. But it doesn’t. You still have to do an enormous amount of testing to get any real quality. And by the time you’ve done all that testing, static type checking winds up being superfluous.

Things get even a little worse if we want to process the map in an ordered way, and we assume that the original map isn’t necessarily ordered.

Here’s the Ruby expression:

map = getInfo();
map.sort.each { |key, value|

Pretty cool, huh? You merely invoke an intermediate sort() method to get the result you want. It’s even more readable because parentheses on method invocations are only required when they are absolutely necessary.

Here is the equivalent operation in generified Java:

Map map = getInfo();
Map sortedMap = new TreeMap(map);
for(Map.Entry e : sortedMap.entrySet()) {
String key = e.getKey();
Object value = e.getValue();

Readable? I think not. It takes more than a quick glance to tell what that code is doing.

By the way, I used to love Artima, back around 2002-2005, and I learned about a lot of new languages there, but lately it seems to be mostly focused on Flex and Scala. Why is that?