A blog by Clint Combs

There are many in the development community that keep raving about dynamic languages. I've used Groovy for several small projects and I see why people like it, but I'm not a big fan of the lack of compile-time type safety. I'd like to see a language that provides many of the syntax enhancements (closures, map syntax, etc.), but preserves the safety. For this reason and yesterday's experience with a ClassCastException, I'm looking forward to Java Generics.

Yesterday I was modifying an old "TODO" in my code related to the getParameterMap() method on the ServletRequest interface. Before the Servlet 2.3 spec, this method didn't exist. Seeing the obvious need for such a beast I had crafted my own before 2.3 was introduced. However, my method returned a Map instead of a Map. The same return type, you say? No.

When putting together this method for myself, I didn't care about the possiblity of multiple values for a single key. As a result my Map was, in the generics type syntax, Map<String, String>. However, the servlet spec implements the full semantics of a request parameter and returns multiple values via a Map<String, String[]>.

Forgetting that I had implemented my method this way, I merrily substituted the old method call with the Servlet 2.3 call and restarted my app. I didn't expect to get a ClassCastException, but that's exactly what I got. After puzzling over this for a while, I finally noticed the difference in return types and fixed the problem.

Yes, I know it would have been advisable to pull up junit and write a unit test first, but I still would have run into the same issue. Also, the method was only called in one place in my code. So I got to spend a little time running my debugger and figuring out this seemingly simple problem. Simple is right, even the compiler could have caught it, if the code was written with generics.

I'm looking forward to the day when generics are widespread. I'm already building all my personal projects in JDK 1.5 and it's made a big difference, but the real win will come when APIs like the servlet spec start making use of generics.