too much TemplateMethod

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.

2 thoughts on “too much TemplateMethod

  1. Always seemed to me that Template Method worked best to enable extensibility – that is, to allow subclasses to attach additional behavior to algorithms. Also works well within Strategy itself to allow partial strategization. You’re right, though – too much is not a good thing.

  2. I remember chatting with you about the use of Strategy in Ruby – compared to the pain in most other languages – early last year sometime, so I’m surprised you’ve not been rolling it out more. I suffer the reverse problem, where I’m happy to start with an empty object and build it. The ultimate Factory?

Leave a Reply to John Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s