Search This Blog

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.

2 comments:

Anonymous said...

Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my blog, it is about the Celular, I hope you enjoy. The address is http://telefone-celular-brasil.blogspot.com. A hug.

Anonymous said...

Great work.