ObjectA calling ObjectB

Alan Gauld alan.gauld at btinternet.com
Sat Dec 27 19:10:26 EST 2003


On Sat, 27 Dec 2003 21:37:07 GMT, MidasOneTwo at hotmail.nospam.com
(Midas) wrote:
> It looks like you hardcoded the name ObjectB within ClassA. 
> I'd like to avoid all hardcoding of names. In other words, 
> I'd like ObjectA to be *told*, at run time, which object 
> to call and which method to call.

While what you ask is possible it does kind of mess up the ideas
of good OO design. For this to happen the caller of A's methods
must know that A contains a B (not too bad but not pure OOD) and,
much worse, know that B contains a method called foo which it
tells A to call.

The law of demeter suggests you should create a method on A that
knows what to do, which may entail calling a method on B but it
may equally entail looking up a third object which is a message
dispatcher or ORB and getting it to do the work. The client of A
shouldn't really know how A's internals work.

So I guess I'm querying whether your design is as decoupled as it
should be. The only thing that should know what A has inside is
A... To do what you request something outside of A has to know
about B, give it to A then request A to call a known method of
the B givento A. Why not just have the external agency manage B
directly since it is already tightly coupled to it?

However I can equally guess that in the real world there may be
some cases, especially in data driven applications where you want
to dynamically control the internals of A, although even there
creating a dispather mechanism may be worth the extra work...

Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Python-list mailing list