[Tutor] design?--having subclassed methods add logic in the middel
of class methods
Brian van den Broek
bvande at po-box.mcgill.ca
Tue Feb 22 00:37:52 CET 2005
Kent Johnson said unto the world upon 2005-02-21 16:40:
> Brian van den Broek wrote:
<SNIP>
>>
>> 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?
>
>
> Yes. This is an example of the Template Method pattern. It is a very
> useful technique for allowing subclasses to specialize an operation.
> http://home.earthlink.net/~huston2/dp/templateMethod.html
Hi all,
thanks for the link, Kent. I came up with something that has a
non-pejorative name? I must be getting warmer! ;-)
<SNIP my code sketch of how to do this `Template Method Pattern'>
>> 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.
>
>
> No, IMO it's a reasonable design.
>
>>
>> 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
>>
<SNIP example code sketch>
>>
>> Are there general reasons to prefer one approach over the other?
>> Alternative ways I've overlooked?
>
>
> They are both template methods. I would choose between them based on
> whether there is common processing between the subclasses or not. In
> other words, in the version with _subclass_preparse() is there actually
> some work for the base class to do after _subclass_preparse() is called?
> If so, _subclass_preparse() might be a better design; if not, you might
> as well just use _parse_line().
Thanks for the advice; useful as ever. :-)
Best to all,
Brian vdB
More information about the Tutor
mailing list