Index: [thread] [date] [subject] [author]
  From: Jay Steele <jes22@duke.edu>
  To  : 
  Date: Wed, 28 Apr 1999 00:31:36 -0700

Re: instanceof

I thought that one of the reasons for implementing observers was to
separate the output from the other aspects of the game.  To me, this seems
to imply that objects such as players and items should have no idea how to
output themselves.  All output would  be handled by the observer.  So, how
would you determine what the object is (the user, an enemy, a network
player) with out using instanceof?  If you use the command interface as
suggested, to me it means that somewhere outside of the observer it is
being decided how stuff, such as players, should be outputted.  This seems
to create a conflict in what we have been told to do.  Is it now okay to
determine output before reaching the observers?

jay


Garrett Mitchener wrote:

> 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]