dev@glassfish.java.net

Re: instanceof switch statement

From: Tom Mueller <tom.mueller_at_oracle.com>
Date: Fri, 10 Dec 2010 09:29:07 -0600

  +1.

On 12/9/2010 6:45 PM, Bill Shannon wrote:
> 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.