dev@glassfish.java.net

instanceof switch statement

From: Bill Shannon <bill.shannon_at_oracle.com>
Date: Thu, 09 Dec 2010 16:45:36 -0800

Recently I've come across two instances of what's effectively a
switch statement implemented using if/else and instanceof, e.g.,

        if (x instanceof A)
            compute y for A;
        else if (x instanceof B)
            compute y for B;
        else if (x instanceof C)
            compute y for C;

This is obviously completely non-extensible and fragile. What happens
when "D" is introduced?

Seems to me the above is better done by adding an interface that A, B, and C
implement that has a "compute Y" method, and letting A, B, and C each do their
own specific computation of "Y".

Do you agree?

I suppose I can imagine some cases in which this might make sense
if doing the computation for Y caused greater coupling between A, B, C
and Y than is desired, but in the cases I've seen it was more the opposite.
The code above had far too much knowledge of A, B, and C.