Search This Blog

Loading...

Wednesday, July 4, 2007

Code review

During a code review I stumbled accross the following code:
SomeObject someObject; 
if(o instanceof SomeObject) {
someObject = (SomeObject)o;
} else {
throw new ClassCastException("Cannot cast=[" + o.getClass() + "] to expected class=["+ SomeObject.class + "]");
}

Obviously the throwing of the ClassCastException is redundant. You can replace the above code with the following statement:
SomeObject someObject = (SomeObject)o; 

This statement doas semantically the exact same thing! At runtime a ClassCastException is thrown when object o cannot be cast to SomeObject. By looking at the stacktrace you can figure out where in your code things go wrong.

Moral of this story: use code reviews to improve the quality of your code.