Index:
[thread]
[date]
[subject]
[author]
From: Garrett Mitchener <wgm2@duke.edu>
To :
Date: 27 Apr 1999 21:30:46 -0400
Re: instanceof
Just because its type is Object doesn't mean you don't know what it
is. If you have a convention that only objects implementing some
interface get passed through, all you have to do is cast them. The
cast is supposed to always succeed, and if it fails, your program is
buggy. Instead of this:
> public void update(Observable o, Object arg)
> {
> if(arg instanceof java.awt.Canvas) {
> ((java.awt.Canvas)arg).update();
> }
> else if(arg instanceof GamePlayer) {
> ((GamePlayer)arg).takeTurn();
> }
> // etc.
> }
>
may I suggest this:
public interface Command
{
public void doStuff();
}
public class CanvasUpdateCommand implements Command
{
...
}
public class GamePlayerTurnCommand implements Command
{
...
}
class SomethingObserver implements Observer
{
public void update(Observable o, Object arg)
{
((Command)arg).doStuff();
}
}
If you always send a Command-implementing object through arg and make
that a documented convention, then it's okay for that cast to fail
because it means you've made a programming mistak.
A more likely thing is that you will make arg something that tells the
observer which things have changed in the observable.
The long and the short of it is that if you are using instanceof and
an if-else chain, you are limiting yourself. Replace that kind of
thing with a virtual function, and you can add any number of
possibilities without re-writing any existing code, which is very much
the point of OOP.
-- Garrett :-)
Index:
[thread]
[date]
[subject]
[author]