according to Twitter subscribe to my twitter feed

    Generics in Java are not so bad. Stop your moaning!

    It seems a commonly held belief that due to type erasure, Java's implementation of generics is somehow tainted. I mean, it is just compiler magic right? The comparison with the .net languages is a frequent one. Having generic type information availble at runtime certainly has benefits in that reflection works and the .net CLR is able to make more optimisations by avoiding the casting / boxing overheads.

    The argument for Sun's decision to go with type erasure - backwards compatibility - is well appreciated. However, I didn't realise until recently that generics were bolted onto .net after the initial release. Obviously Microsoft didn't wait as long as Sun did, but they were definitely not there from the outset. So, all of the same compatibility problems that Java suffered applies to net too. But, as Microsoft opted for the non-backwardsly compatible route and allowed reifiable types, they essentially deprecated all of the existing library classes that work with non-generic types.

    Which in many ways seems like a real shame. From a purely aesthetic point of view, C# is a very elegant language that neatly avoids a lot of Java's legacy cruft. What a shame to have a whole package of non-generic collections classes sitting in the background like a wart on the core API. And so early on in the language's lifetime.

    Here's another example. As Enum already existed in C#, it could not be generic-afied (pretty sure that is not a verb...) without breaking all existing usages. So Enum in C# does not have a crazy looking definition like in Java:


    public abstract class Enum<E extends Enum<E>>
    extends Object implements Comparable<E>, Serializable


    (Angelika Langer has the best explanation of this initially baffling splurge of brackets.

    Which means that parsing a String to an enum value cannot be done in a typesafe way, and takes some hoop jumping in C#:


    // Parsing String to Enum in C#
    Colour colour = (Colour)Enum.Parse(typeof(Colour), "RED");


    Compare this to the elegant version possible with Java's api:


    // Parsing String to Enum in Java
    Colour colour = Colour.valueOf("RED");


    It feels like a missed opportunity. The brave decision was to break backwards compatibility for the sake of a purist and better functioning approach to generics. Pity then to sidestep the controversy by not applying this to all of the existing libraries - C# is already saddled with crufty code in its core libraries.