Harmful Generics

by Kieran

A few years ago, whilst I was using Java 1.4 I was introduced to the newer features of Java, more notably generics.  Once I had learnt how to use them correctly I thought they were an absolute blessing from the monkeys at Sun.  More recently, however, I’ve had a number of people point out to me that they’re not as useful as one may assume them to be, and in fact cause more problems rather than solve them.  The reason I use generics is for applications that deal with objects at such an abstract level that they could never really determine what type of object they are unless some seriously awful code was lurking around (which I have been known to do).

I was writing an application dealing with Shape objects, with a lot of help from a certain someone.  I had to be able to draw Shape objects to screen but without knowing their type as they were being serialized and received over a network connection.  I literally couldn’t find out what type of object they were unless I did some very static type checking, which is something I wanted to avoid.  Furthermore I had a draw(Shape s) method which took the generic type and drew it to screen using its own method with the correct graphics context.  So in this case I ended up calling s.draw(g); which is a solution I admittedly found over at Java Ranch.  In my opinion, using generics in this case is absolutely fine, because there is a type hierarchy, and it is ever-expanding so the abstract approach using generics was beneficial.

Ken Arnold clears up some of his issues with generics by looking into recursive (or circular) types such as Enum<E extends Enum<E>>, something which scares the crap out of me, that’s for sure.  However, if you read through the comments you’ll find some insightful comments on generics, namely that they were poorly introduced, or they shouldn’t be mixed with arrays whatsoever, and as some people point out, C++’s template system is far more complex.  I’d like more insight into this area as for me generics are a day-to-day, run-of-the-mill usage of language features.  I actually don’t know how else I would approach problems without them.  Perhaps this could be compared to activists who disagree with OOP?

Note: I am aware generics was a Java 5 feature, it’s just it was previewed during Java 1.4 ;)


Rss Commenti

No Comments

No comments yet.

Post a comment

You must be logged in to post a comment.