Recently Classpath’s generics branch was merged to be the main line. This means all future Classpath releases will use generics, and now we’re free to use other Java 5 features in the Classpath source.
When we started the generics branch we made a conscious decision to do a “shallow” translation to generics — we rewrote method signatures and visible field signatures, but not the bodies of methods. This was done so that we could more easily merge changes on the trunk to the generics branch, a smart decision considering that the generics branch lived for two years.
This weekend I spent some time adding generics in a deep way, that is, modifying the bodies of methods to properly use generics, and attempting to remove all the warnings related to raw types, unchecked casts, etc. Aside from random warning removal, I had a specific question in mind: how much reliability do generics add?
I completely converted about 5 components (meaning some core package plus all its support code). In all of this I found 2 actual bugs. (Also I once found a bug in imageio on the generics branch during a shallow conversion, bringing the known total of bugs found by generics to 3.)
In one case we were making an invalid assumption about the actual return type of
Collections.toArray() (and, btw, this particular API can only be truly fixed by reified generics; in a sense we were lucky to catch this bug).
In another case a protocol implementation had made an incorrect assumption about the types of the contents of a collection it returned.
I have to say I was very surprised by this result. Generics are somewhat tricky to use, add a lot of verbiage to the source (especially since Java doesn’t yet have C#’s
var, aka C++’s
auto type inference feature), and now, apparently, don’t really catch very many bugs.
There are a couple other theories to consider other than “generics aren’t worth it”.
One is that Classpath, being a core library, is unusually less susceptible to bugs of this kind than other Java programs. I don’t consider this very likely, but more experience with other programs would be useful.
Another is that the Classpath development process is unusually good and catches more bugs than normal. This would be nice if it were true, but I doubt this is very likely either.
Finally, one could argue that catching even a small number of bugs in legacy code is good, and that the real worth of generics comes when writing new code.
I’ll collect more data as we convert more of Classpath to use generics deeply. I’m curious to know whether other folks have had more positive experiences during conversion, or whether there’s something I’m missing about all this. At the moment generics appear to be “nice to have” but hardly worth the substantial upgrade effort across the toolchain and the large body of existing Java code…