[Advanced-java] How To Determine The Appropriate Exception?

Paul Philion philion at acmerocket.com
Fri Aug 8 19:27:51 2003


Silvio -

My opinion is simple: 99% of the time, more readable code is better than 
"faster" code.

I find that code much more obscure than:

public void m1(ClassA ob) {
     String x = "Default Value";

     if (ob instanceof ClassB) {
         ClassB b = (ClassB)ob;
         x = b.someMethodOfClassBNotDefinedInClassA();
     }
     ....
}

IMHO, the version above is easier to read, easier to debug and easier to 
maintain.

Of course, if m1() is being called inside a tight loop, millions of 
times, and a profiler shows that "instanceof" is taking up a lot of 
time, and performance is paramount, then I can see implementing that 
call you have below. I would also add a comment explaining exactly what 
was being done, and why.

But without those justifications, I would always prefer to test than 
deal with the confusing code.

-- paul philion

Silvio L. de Morais wrote:

> I like this kind of discussions.
> To keep on the same subject, I would like your opinions on
> a simple technique I use sometimes.
> Whenever I have a method that receives a generic base class
> as parameter (could even be Object), and I have to call a
> specific method defined on a derived class, I do this:
> 
> public void m1(ClassA ob)
> {
>    String x;
>    try {
>        x =
> ((ClassB)ob).someMethodOfClassBNotDefinedInClassA();
>    }
>    catch (ClassCastException cce) {
>    {
>        x = "Default Value";
>    }
>> }
> 
> My rationalization of this is: 'Most of the time the cast
> will be correct, and I will not have to use the more
> expensive "instanceof" operator all the time'. But I was
> criticized before on a code review because it is not a good
> use of Exceptions.
> What do you guys think?