Saturday, June 26, 2004

Static typing and Java collections

Java's collection classes provide fertile ground for the perpetual debate between static and dynamic typing. One argument says that since Java collections are effectively dynamically typed, but ClassCastExceptions are still rare, static typing may not be as helpful as its advocates would like to think.

I ran into a ClassCastException the other day. My initial thought was to count this as a place where static typing wins out, but once I found and fixed the mistake, the particulars paint a rather different picture.

  • The container in question was HttpSession attributes - a heterogenous collection that cannot be made typesafe by generics or similar mechanisms.
  • The cast that caused the problem was because I put a Collections.synchronizedSet(new HashSet()) in the session, and tried to take a HashSet out. In a dynamic language, this wouldn't be necessary - if it acts like a set, it's a set.
  • This is not the kind of bug that lays dormant in code for long periods of time. The compiler didn't catch it, but my unittest did.

Even though Python is my favorite language overall, I tend to believe that static typing is valuable for large projects. The aforementioned Bruce Eckel article says that static typing is a form of testing, but I think it's really more like documentation. Type declarations are a form of comment whose accuracy can be verified by the compiler. In a dynamic language you usually end up putting comments describing the types of objects, so you might as well do it in a machine-readable way.

0 Comments:

Post a Comment

<< Home