Design flaws with Java Generics

ziggy on 2004-03-12T22:28:13

Another episode of Java-inspired Schadenfreude...

Bruce Eckel wrote up his observations on what's broken on the proposed Java Generics feature proposed for inclusion in the next version of the Java language (JDK 1.5).

Instead of ranting about what's wrong with Java (like many of us are wont to do), Bruce looks at the intention behind generic programming, as practiced in languages lilke Python, Ada and C++. Python, like Perl, uses an idea Bruce calls "latent typing": instead of performing operations based on a specific set of (static) types, you want to write code in terms of what kinds of operations those objects can perform.

Here's a Perly example:

## get a group of heterogeneous objects
my @bag_of_objects = ....;  

foreach my $obj (@bag_of_objects) {
    $obj->pour();
}
Inside that foreach loop, $obj can be anything that can have a pour method: Vodka, Tequila, Salt, Whiskey or Gin. It doesn't matter. (If you pass in something like a Car, you'll get a runtime error, silly programmer. Cars and Whiskey don't mix.)

As currently designed, Java Generics are syntactic sugar for casting objects all the way up to java.lang.Object and, in some circumstances, casting them back down to some more refined type. The problem is that once cast back to Object, you cannot invoke any methods on your parameters. In his first article, Bruce demonstrates that the best you can do with Generics is no better than what you can do today, and in fact, it's worse.

Bruce does a very good job arguing that at worst, you want something like the C++ model (static type checking, full range of operations). But really, what you want is something closer to the Perl/Ruby/Python model of trusting programmers to say something sensible with generic values.

Put another way, what you want is Perl, or at the very least, Python. ;-)

Bruce's second article is the best refutation I've yet to read against small-minded B+D languages. For all of its flaws, C++ has been beaten into shape as to allow you both early binding/static typing and generic programming features. Java, on the other hand, insists on early binding and static typing -- all of the pain with none of the benefits. Bruce further relates this notion to Martin Fowler's recent observation that these are embedded attitudes in how we think about software. Are languages tools to restrict how programmers think (in order to keep them from shooting themselves in the foot), or are they tools to help programmers solve problems using the most natural expression available? The attitude behind Java Generics smacks of the first approach....