[Tutor] Dependencies among objects

Alexandre Ratti alex@gabuzomeu.net
Thu, 25 Apr 2002 14:47:30 +0200


Hello,


while working on my pet project, I find it increasingly difficult to manage 
dependencies across objects.

Some classes defined objects that are used throughout the app (a page index 
and a full-text index for instance). Other classes might need one or more 
of these objects to work properly (eg. macros that carry out special tasks 
for instance).

Passing around lost of references as arguments is getting messy. Hence I 
thought about this design: storing references to helper objects in a parent 
class so that every child class can access it easily.

Here is an example:

##
class BaseObject:
     pass

class Foo(BaseObject):
     """Helper class used by several
     other classes throughout the app."""

     def __init__(self):
         # Do initialisation stuff and register self
         # in the parent class.
         BaseObject.foo = self

     def getValue(self):
         return "Value from Foo"

class Bar(BaseObject):
     """Class Bar need a foo instance
     to perform some task."""

     def doIt(self):
         value = "I am Bar and I use '%s'."
         return value % BaseObject.foo.getValue()

if __name__ == "__main__":
     # Initialised somewhere when the app starts up
     foo = Foo()
     # Instance that uses foo through its parent class.
     bar = Bar()
     print bar.doIt()

 >>> I am Bar and I use 'Value from Foo'.
##

Do you think this is a good design?


Thanks.

Alexandre