Sunday, July 21

Item 23 : Don't use raw type in new code

What is new code?

Code written using release 1.5 onwards in new code. Generics are included in release 1.5
Why should we switch to generic type?

Generic types provide compile time type safety and it's good in programming to know the error as early as possible.
ClassCast exceptions that generally are unraveled only at runtime type would know detected at compile time itself if Generic types are followed.

For example :

1. List list ; // List of Horse.

2. list.add(new horse());
3. list.add(new Dog());

4. while(list.hasNext()){

5. Horse horse = list.next();

6. }


Line 5 , will throw ClassCasException as It tries to assign an instance of Dog class to Horse Type.

list is just the list of horses but mistakenly Dog is also added to that. Compiler did not compliant while adding Dog as the type of list is not specified . It's raw type list. Now the mistake skipped by Compiler costs heavily at runtime and program failed due to ClassCast Exception.

Now the Question Is Could that be avoided. Could we smell the the error earlier?

Yes , we could ask the compiler to detect the menace just by using generic type list.

1. List<Horse> list ; // List of Horse.

2. list.add(new horse());
3. list.add(new Dog());

4. while(list.hasNext()){

5. Horse horse = list.next();

6. }

at Line no 1 , list is defined to be Horse type So compiler already knows the type of list . It would complain as soon as you add Dog to the list.

Thus using generic type enforce the type safety check at compile time itself and there It can be corrected and heavy runtime burst is avoided.

No comments:

Post a Comment