Design Question

Robert Ferrell ferrell at diablotech.com
Tue Jan 13 12:28:59 EST 2004


I have a question which is more about OO design than Python per se. 
I've noticed that a number of posters to this list have very good
suggestions for SE issues, so I'm hoping that someone will be able to
give me some guidance.

My question is about how to architect a class hierarchy where some
methods are nearly identical between a superclass and a subclass, but
differ slightly.  For example:

class Sup(object):
   def __init__(self):
      self.specialFlag = False
   def aMeth(self):
       <do some stuff>
       <if self.specialFlag, do a special thing>
       <do more stuff>

class Sub(Sup):
  def __init__(self):
    self.specialFlag = True

In this example, the method aMeth just checks for specialFlag, and if
it's True, does the special stuff required.

This allows me to share aMeth, and not have to duplicate code. 
However, this doesn't feel great to me because Sup has to know about
Sub in some fashion.  If later I add other subclasses with their own
special needs, the entanglement will just get worse.

An alternative I thought of was creating a module with helper
functions.  That module would contain a function which implements
whatever aMeth does, and knos about the special needs of Sub.  Both
Sup and Sub would invoke the helper method.  That allows me to share
code, avoids a direct dependency of Sup on Sub, but does add a new
module.

I'm guessing that there is some well known pattern that addresses this
issue, but I don't know what it is.  Does anyone have suggestions for
architecture that provides a good solution?

thanks,
-robert



More information about the Python-list mailing list