too much TemplateMethod

Posted on January 4, 2009

2


I’ve been refactoring a lot during the festive break, and I’ve noticed that in many cases it was more difficult than I would have liked. Today I think I figured out the reason for that: I use the TemplateMethod pattern too much.

When I see a duplicated algorithm, it seems that my natural tendency is to push up the skeleton into a superclass. This creates an inheritance relationship within the algorithm, which in turn makes it harder to change. Later, when I do need to change the algorithm, I have to change the superclass and all of the subclasses at the same time. For example, one particular superclass in reek contained three or four template methods, which made the subclasses look quite odd; and each little complex of template-plus-overrides significantly hampered design change in each of the others.

Looking back over my programming career I see that I’ve always had this tendency — I can see it in my old C++, Java and Ruby code. I wonder why? Is it the cost of extra classes, or my mathematical background, or coding habits ingrained before the rise of object-oriented languages? Who knows (and who cares).

So, note to self: Break out State/Strategy objects (and in Ruby this includes Procs) instead of always relying on TemplateMethod.

Tagged: ,
Posted in: design, reek, refactoring