Çarşamba, Kasım 14, 2007

Why type casting is bad and generics are good?

The current version of java supports generics, thank god. Before this people using Collections,Vectors, and/or any other type of Linked list based data structure would have to cast the objects within to their corresponding types when accessing the data. Type casting is dangerous!. Consider the following example:

Vector v = new Vector();
for (int i=0;i<15;i++) {
v.add(new MockObject(i));
}

The vector v now has 15 objects of type MockObject. We didn't use generics here. Now lets get those MockObjects back:

Iterator it = v.iterator();
while(it.hasNext()) {
MockObject mo = (MockObject) it.next();
mo.mock();
}

We type-cast the objects in the vector to MockObjects. That would seem ok, for one person who is writing a small piece of code but when things get complicated, this is a trap, ready to explode into a
big bug fest.

Let's take a look at the following method of the object UselessObject:

class UselessObject {
public void uselessMethod(Vector v) {
Iterator it = v.iterator();
while (it.hasNext()) {
MockObject mo = (MockObject)it.next();
mo.mock();
}
}
}

look's like a harmless class with a harmless method. But no! This is a very dangerous thing to implement in a java environment that does support generics. Because enventually someone will do this:

UselessObject uo = new UselessObject();
uo.uselessMethod(myVector);

Boom! Hah! What just happened? Why did my application explode?
The thing here is that we are type casting the objects in myVector to MockObjects, with out even having a clue that they are MockObjects. This leads to class casting exceptions and bug fests that cant be detected at compile time.
Generics come in handy at a time like this. The code using generics would be like this:

public void uselessMethod(Vector<Mock> v) {
...
..
}

and would only except a Vector, which is filled with objects of type Mock.

0 yorum: