Sunday 20 September 2009

Item 24: Eliminate unchecked warnings

This item discusses the new unchecked warnings introduced into Java to support generics. Java still supports the old style code without generics to be compatible with existing code. But new development should use generics. The unchecked warnings inform the developer that the code might be using generics that is not typesafe. So this item recommends that all unchecked warnings are eliminated by using generics properly. Basicly listen and act to the messages from the compiler. This might be challenging but the code will be better for it.

If the developer believes that the error can't be removed and that the code is type safe, then the annotation @SuppressWarnings("unchecked") can be used. This will tell the compiler not to report the warning. This should be used on the smallest scope as possible. So other unchecked warnings are not suppressed unnecessarily.

If @SuppressWarnings("unchecked") is used but the code is not type safe, the code could generate a ClassCastException at runtime. So the developer must prove that the code is type safe and a comment should inform others why the annotation was used and why it is typesafe.

Timothy Wright

No comments: