Tuesday, October 23, 2007

Proper use of Generics

Yesterday I was asked to review code written by an ex- colleague of mine for a particular module. As I was reviewing I came across these lines of code

Snippet of the code:-
--------------------------
Node node = // does something to the get the node;
List < object > nodes = new ArrayList < object >();
nodes.add(node);

As soon as I saw this I educated him on the proper use of generics. It should have been written this way

Proper snippet of the code:-
-----------------------------------
Node node = // does something to get the node
List < node > nodes = new ArrayList < node > ();
nodes.add(node);

This brings in type safety and the compiler ensures that you only add objects of type node into this list. As we all know that Java is a strongly typed language and the addition of generics to the Java API has only increased the type safety.

1 comment:

Ganesh said...

Nice catch buddy, I do agree. Thats the basic purpose of the Generics. I think your ex-colleague using Generics because he has to use. :)