TechBookReport said:
Does anybody have a good word to say about generics in J2SE 5.0?
It appears that most of those spouting off about the evilness of
generics are dynamic typing fans. If you don't like static typing, then
you aren't going to want more of it. If you do like static typing, it
might as well be done properly.
I can't
help thinking it's a sledgehammer to crack a nut. Casting into and out
of collections wasn't such a big deal.
No it's not a big deal. Although it is ugly, tends to lead to
unnecessary code and the source is complicated precisely where you want
it as simple as possible.
Sure type-safety is important,
but the implementation is intrusive and ugly (aesthetics seem important
to me). If anything surely the class cast problem is something that
intelligent tools like Eclipse or NetBeans could have solved without
resorting to language changes.
ClassCastException is a red herring. Searching through the Bug Parade
brings up seven times more bugs with NullPointerException than
ClassCastException.
Particularly as erasure means that it's
only at compile time that generics provide a benefit.
Given that we have such good static type checking, runtime type checking
is an obscure feature. Having said that, as 1.4- isn't targeted, I would
have preferred a JVM level implementation, particularly for covariant
return types (which still have outstanding bugs).
It's not a valid criticism coming at it from a dynamic typing point of
view, anyway. You can't, as I understand it, take a Smalltalk collection
and ask what shapes will all its contents, past and future, will conform to.
The real issue, assuming you welcome static typing into your life, is
documentation. It's much easier to understand what is in Set<EmployeeID>
than Set with the element type hidden amongst the JavaDocs if at all and
if kept in sync.
For instance, modifying a JRoller Velocity template, many of the methods
return Lists. But the documentation (often) doesn't (didn't) say what
they contain. I've inherited code that accidentally used the same map
for two different mappings. That only became apparent because, coming
from C++, I used to put type information within /*< >*/.
I find JavaDoc Use pages useful in understanding how a piece of code
fits together. In olden days, if you didn't use arrays, you didn't get
to see a lot of important relationships. In one case, I was witting the
public API documentation to a product and wrote in on the type
description the missing uses. Shortly after that the PSE changed the
Collections to arrays. But really, we would like to encourage the use of
interfaces over nasty arrays.
While some people coming to generics might find them confusing, if they
push their minds back far enough, they probably found polymorphism
confusing too. They are essentially the same thing, just with a layer of
indirection. Perhaps it will take a while for texts to become stable.
Tom Hawtin