[Tutor] design?--having subclassed methods add logic in the middel of class methods

Brian van den Broek bvande at po-box.mcgill.ca
Mon Feb 21 21:02:18 CET 2005


Hi all,

I am still building my toolset for working with treepad files. (This 
is the one all my recent posts concerning Node classes have been about.)

I am exploring ways of having the methods of a sub-class insert 
additional logic into their version of a class's methods, while still 
running the original class's method logic.

All code below is pseudo-code.

My Node class has a parse method which in part looks something like:

def _parse(self, list_of_lines):

     # some parsing based on whole list_of_lines

     for line in list_of_lines:
         # Do line parsing stuff here

In a subclass of Node class, I am wanting Subclassed_Node._parse() to 
behave somewhat differently than does Node._parse(). I need the 
subclass method to insert new logic into the for line in list_of_lines 
part of _parse method.

Is this an acceptable design for doing this?

# in Node class

def _parse(self, list_of_lines):

     # some parsing based on whole list_of_lines

     for line in list_of_lines:
         _subclass_preparse(line)
         # Do line parsing stuff here

def _subclass_preparse(self, line):
     '''Dummy method to override'''
     pass


# in Subclassed_Node class

def _subclass_preparse(self, line):
    '''Subclassed_Node class specific parsing, overrides Node method.'''
    # Do special parsing of the line here here

Does this scream `Danger -- spaghetti code will result down the road'? 
The method name containing `preparse' indicates I might also feel a 
need for a `postparse' structure, too.

The only viable alternative I see (copy and paste is clearly worse ;-) 
is to break my Node._parse up into a part that works on the whole 
list_of_lines and a part that works on each line as in

def _parse(self, list_of_lines):

     self._parse_list_of_lines(self, list_of_lines)

     for line in list_of_lines:
         self._parse_line(line)

def _parse_line(self, line):
     # line parsing logic here

Then the subclass of Node would define _parse_line like so:

def _parse_line(self, line):

     # line parsing logic before the Node class line parsing logic
     # akin to _subclass_preparse above

     Node._parse_line(self, line)

     # line parsing logic after the Node class line parsing logic
     # akin to the possibly needed _subclass_postparse mentioned above

Are there general reasons to prefer one approach over the other? 
Alternative ways I've overlooked?

Best and thanks to all,

Brian vdB



More information about the Tutor mailing list