[Tutor] communication between class instances

alan.gauld@bt.com alan.gauld@bt.com
Sun Dec 8 18:33:01 2002


Because I'm reading this digest way late this has likely been
answered already, however here goes my take on the subject...
(regular readers probably know what I'm gonna say! )

> So far, instantiating classes and passing references to all 
> other class instances that the instance will need to 
> communicate with is the only way I've come up with to 
> get class instances to communicate with each 
> other.  

That's the normal way of doing it except...

> a better way to pass data between class instances?  

...You shouldn't be thinking about passing data you should 
think about passing messages. Its a subtle but important 
distinction. A message may of course contain a reference 
to an object.

Of course for an object to send a message to amother object 
it must somehow get a reference to it. The reference could 
come in as part of a higher level messaage or it could be 
stored as a member attribute (maybe set up during initialisation)

So we have a few alternatives. What do we do?
Think about responsibilies. Decide which classes are "managers" 
of other classes - the GUI might manage the menu in your case...
The app ultimately manages everything, but it does so my 
delegating responsibility across a relatively few subordinate 
classes which it stores and talks to itself. In your case 
the app probably should know about the database and the 
GUI but not the menu. The GUI/DB possibly want to hold references 
to the app too, so they can send messages to it(done by passing 
self in from the app during initialisation). 

Any menu things going on should be controlled by the GUI. 
When the menu is created usually a callback function 
is passed to each menu item. This is probably done by the GUI 
but the callback could be an app level function obtained by 
the GUI via the link back to the app.

At this point we begin to see why OO designers like to draw 
diagrams to show the interconnections between their classes!

> is having to pass a reference to the app instance all the way down to 
> the menu instance, which really should only be aware of the 
> gui instance which instantiates it. Right?

It needn't even be aware of the GUI. The GUI will be aware of 
the menu but the menu doesn't need to be aware of the GUI. It 
may have a callback link to a specific function but it doesn't 
care where that function/method exists

> Right?

Pretty much yeah.

> I'm very confused...

Don't worry the apparent lack of structure in an OO design is 
one of the things that makes adapting to OO thinking a steep 
learning curve. Some folks find it natural, most find the seeming 
anarchy ghard to get a grip on.

HTH,

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld