« Horn | Main | 100 lines »

Generics Considered Harmful

Ken Arnold has posted a blog entry about why he considers generics to be a mistake in Java.

Here are my generics pros and cons

Pros:

  • Static type safety. Where possible I prefer static check which cover the entire code base to dynamic checks which will only ever test one particular execution path. Static type safety makes me feel safer.
  • More expressive code. I like being able to say that I'm creating a map from URI->BufferedImage if thats what I'm doing. It makes the code easier to understand.
  • Less duplication of code. Anything which prevents me having to duplicate code because it only differs in the types it uses is good.

Cons:

  • Almost never catches any bugs. I've never personally found that adding generics caught any more bugs than before.
  • Not uniformly applied. The use of generics in the Java libraries is pretty sparse. It only seems to be used in the core (lang/util) packages. The model/view/renderer/editor elements in Swing would probably benefit from having explict types passed around.
  • Added language complexity. While the use of generics on the collection classes is straight-forward, as soon as you stray outside these bounds it becomes incredibly complicated.

So are generics worth the cost?

Well, I ordered the pros and cons in a way that the cons cancel out the pros. So static type safety is cancelled out by the fact that it almost never catches any bugs. More expressive code is not much use if its only partially done. And is the cost of complexity worth the removal of duplication?

I guess generics probably aren't worth the effort, just find a good naming convention for your collections, and you'll get most of the benefits.

Comments

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment