Tuesday, May 5, 2009

TMA or simply Polymorphism?

Template Method Algorithm aka TMA (GoF) has been my all time favorite among Design Patterns. You can find a very good explanation of TMA in 'Head First Design Patterns' as it sheds light on some aspects even missing in GoF. Here are some slides on TMA that I made few years back:

Simply put, it streamlines the most trivial usage of polymorphism. This makes it a candid member of many compound patterns.

One pitfall that I have run into on quite a few occasions is when I try to make my base algorithm encapsulate lots of logic in order to maximize code reuse, pulling even minimally repeated piece of code from the concrete algorithms and placing it in the base algorithm. This all seems to be good and powerful until there come changes specific to the concrete algorithms forcing the common logic in the base algorithm to break.
Another trap of this trivial pattern is that it makes it easy to foresee inclusion of code in the base algorithm which lies outside of the algorithm's scope. Yet again, this is due to it's closeness with the polymorphic theme that the distinguishing line between 'simple polymorphism' and 'usage of polymorphism in TMA' starts to diminish.

Hence, following SRP (Single Responsibility Principle) is the key to writing a successful TMA and not transforming it into one of those god classes.

1 comment:

  1. Thanks, for sharing the article it's really worth it! One point about the pitfall you've mentioned and also agreed upon later.. ;)

    "To encapsulate all the logic between the base algorithm is the actual theme of this pattern to set up the outline/skeleton of an algorithm, leaving the details to specific implementations later".

    This way concrete algorithms/subclasses can override parts of the algorithm without changing its overall structure through polymorphism. I don't agree with the statement that changes in the concrete algorithms forcing the base algorithms to break its structural view until and unless the request is to change the overall theme of the structure.


    The base algorithm (Game) which implements by its concrete algorithms (Monopoly, Chess, Poker and so on). Now if you've initially well defined the base algorithm/structure which fulfilled all the requirements of name implies, then concrete algorithms never forcing you to change its generalized behavior.

    Have a good day!! ;)