27.8.09

More on Generics...

My pet peeve with Generics I think is generic methods. They are actually a useful construct. Here's an example (untested) :
static List<Shape> history = new ArrayList<Shape>();
public void drawAll(List<? extends Shape> shapes)
{

history.addLast(shapes);
for (Shape s: shapes)
{

s.draw(this);
}
}

In short, the compile guarantees that the list history can only take in objects of type Shape. So when you pass in the argument shapes to method drawAll, the compiler would have checked the contents of shapes and only allowed them if they were of type Shape.Its a mouthful but adds a lot of type safety.

Now lets look at another way of doing this:
public class GenericsMain {

public <I,O> O getOutput(final I input)
{
return (O) ((String) input).toUpperCase();
}

public static void main(String[] args)
{
GenericsMain main1 = new GenericsMain();
main1.getOutput(100);
}

}
Does this look correct? Its actually compiler-safe. Not that that means its runtime safe of course. There are no guarantees that I or O will be checked by the compiler as it is not. Try to compile and run this. You get a ClassCastException. That's because, at runtime the JVM converts 100 into a new Integer object which we then proceed to cast as a String. Instant implosion.

This is real live code. The idea was that there would be one instance of this class,with multiple if...else constructs. the conditional would check the typeof the input like so:
if(input instanceof String)
That ways all users can benefit from reuse and fill in all possible business objects conditionals and wreck havoc from there on. Not wanting to divert my attention from the solution to this, I will keep away from the ranting. The solution looks something like this:
public class GenericsMain<Integer, String>
Of course it won't solve the problem in this particular piece of code, I'll leave that as an exercise. Using an interface might improve things.

So in end what I want to emphasize is typecasting any object while paying lip-service to generics is harmful. Unchecked conversions like these only throw a warning and you would never know till Mrs. Chadda got a bong instead of a bangle, in production, 5 days after the product goes live.

That brings us to Type Erasure. More on that later.