Tuesday, June 30, 2009

The problem with Java Generics is.... (Redux)

...while pair programming... bill > Hey, we could use generics here. bob > Great, why don't you drive. bill > Sure. What we need is a T here. Replace that return with T. Add another T here, and there you go. We can now use this for all types of things. Compile...check. Great. Let's fire up jetty. bob > Hey, what does that mean? bill > Strange...it compiled ok. Oh! No problem. What we need is to add a ? here, then extends that to type T and that should work. bob > Nope!! bill > Right, if move that ? to here, then use super of not extends, add T here that will work. bob > Sorry, still not happy. bill > Really? But that's it? You have a T, and ?, the word extends or super. Damn! bob > Why not use instanceof? bill > You can't because of erasure! bob > Erasure? The electronic group from the 80s....I kind of liked them. ♪I tried to discover...A little something to make me sweeter...♪ bill > Stop that!! bob > Sorry. bill > No, Type Erasure. When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. bob > Why would you do that? bill > Two words. Backwards compatibility. bob > That's doesn't help us. bill > Welcome to Generics in Java. bob > I knew we should have written this in Ruby!

4 comments:

  1. I think the best part in generics is the cryptic error messages the JVM throws at you when something does not compile.

    "Capture of the flag on the hill failed" or things like that...

    ReplyDelete
  2. I'm going back to singing 80s electronica.

    ReplyDelete
  3. "Erasure? The electronic group from the 80s"

    Stop stealing my lines!

    ReplyDelete