[Tutor] OO refactoring trial ??

Chinook chinook.nr at tds.net
Tue Jun 28 13:31:43 CEST 2005


[[ This message was both posted and mailed: see
   the 'To' and 'Newsgroups' headers for details. ]]

Clarifications:
1) Truth test simplified after a %) by Peter Otten - thanks.  In reality the 
"testit" methods will all be quite different as you might imagine (as will 
the "doit" methods).

2) A final subclass will always return True, so there will always be a valid 
factory (?) result.

====================
Following is a simple trial structure of a refactoring (top-down to OO) 
learning exercise I'm doing.  Whether you call it a Factory pattern, COR 
pattern, or some hinze 57, I don't know what class to use till run time and 
I'm trying to avoid a lengthy "if" sequence, the test sequence is important, 
and to avoid code duplication I'll be using code objects in the "doit" 
methods.

You've already given me many good ideas in previous threads and this is where 
it got you :~)  This works, but would you please tell me: 
1) What you don't like about the approach and/or how I might improve it
2) The implications of using this in a recursive approach (referenced from 
but outside the recursive function).  
3) Any other comments you might offer

Thank you, 
Lee C


=========== ootest.py 
============
class MF(object):
  @staticmethod
  def findit(t):
    for it in MF.__subclasses__():
      if it.testit(t):
        return it().doit
      
class A(MF):
  @staticmethod
  def testit(tv):
    return (tv == 'relates to A')
  
  def doit(self):
    print '# did A #'
    
class B(MF):
  @staticmethod
  def testit(tv):
    return (tv == 'relates to B')
  
  def doit(self):
    print '# did B #'
    
mydoit = MF.findit('relates to B') 
mydoit() 

mydoit = MF.findit('relates to A') 
mydoit()

======== Test run ============== 
Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, 
Inc. build 1666)] Type "help", "copyright", "credits" or "license" for more 
information.
>>> import ootest
# did B #
# did A #
>>> 



More information about the Tutor mailing list