avoiding instanceof
Hello,
in my attempts to master java, I've been reading online resources on the subject. One of these resources (in fact, several :) ) said that it is bad practice to use 'instanceof'. My first question is: why?
However as I am perfectly willing to accept this as true, I started thinking about how to avoid this in my own code. I have something like the following:
DigitalPin[] aPinArray ={null, null,null};
aPinArray[0] =new DigitalInputPin();
aPinArray[1] =new DigitalOutputPin();
if (aPinArray[1]instanceof DigitalOutputPin){
// Do something that cannot be done inside the DigitalOutputPin object.
((DigitalOutputPin)aPinArray[1]).setState(aState);
}
In case it isn't clear, DigitalInputPin and DigitalOutputPin are derived from the DigitalPin class.
My solution in avoiding 'instanceof' would be to create an 'isOutput()'- and 'isInput()'-method in the DigitalPin class and overwrite these in the derived classes. Is this a more elegant solution? Is there a better path to follow?
Message was edited by:
EvilBro
[1419 byte] By [
EvilBroa] at [2007-11-26 15:20:44]

> Hello,
>
> in my attempts to master java, I've been reading
> online resources on the subject. One of these
> resources (in fact, several :) ) said that it is bad
> practice to use 'instanceof'. My first question is:
> why?
>
> However as I am perfectly willing to accept this as
> true, I started thinking about how to avoid this in
> my own code. I have something like the following:
> DigitalPin[] aPinArray = {null, null, null};
>
> aPinArray[0] = new DigitalInputPin();
> aPinArray[1] = new DigitalOutputPin();
>
> if (aPinArray[1] instanceof DigitalOutputPin) {
> // Do something that cannot be done inside the
> DigitalOutputPin object.
> ((DigitalOutputPin)aPinArray[1]).setState(aState);
> }
>
> In case it isn't clear, DigitalInputPin and
> DigitalOutputPin are derived from the DigitalPin
> class.
>
> My solution in avoiding 'instanceof' would be to
> create an 'isOutput()'- and 'isInput()'-method in the
> DigitalPin class and overwrite these in the derived
> classes. Is this a more elegant solution? Is there a
> better path to follow?
>
> Message was edited by:
> EvilBro
Why are both DigitalInputPin and DigitalOutputPin in one array? Doesn't DigitalInputPin have setState?
> Why are both DigitalInputPin and DigitalOutputPin in
> one array?
The whole array represent a physical port. The individual pins can be configured as input or output.
> Doesn't DigitalInputPin have setState?
It does have a setState (it doesn't do anything). The comment above the setState-line was meant as pseudo-code. It represent doing something that cannot be done inside the pin-object.
> The whole array represent a physical port. The
> individual pins can be configured as input or
> output.
Is sound like you shouldn't use inheritance in that case, and it sounds like you should have isIn and isOut in the base class if you want to keep the inheritance.
Kaj