Template Method is one of the design patterns I turn to a lot when building tiny, lightweight frameworks.
Sure it’s been around since dirt, but I count it as a first class citizen in the pantheon of useful patterns, living with its more hyped siblings: DI/IoC, MVC, MVP, etc. (Yes I know MVC is also old as dirt, Smalltalkers). Maybe it’s not as sexy or “cool” but it’s damn handy for building a consistent and testable codebase.
Let’s take a look:
public abstract class TaskBase { public void Execute() { using (TransactionScope scope = new TransactionScope()) { if (this.BeforeExecute != null) BeforeExecute(); ExecuteTask(); if (this.AfterExecute != null) AfterExecute(); LogExecution(); TransactionScope.Commit(); } } public event EventHandler BeforeExecute; public event EventHandler AfterExecute; private void LogExecution() { // write event details to // some durable resource } protected abstract void ExecuteTask(); }
Above I’ve declared an abstract base class (or Layer Supertype if you skew fancy). In this case “ExecuteTask” is our template method. Inheriting classes must implement this method. This is where the work of our “Task” implementation actually gets done.
What’s cool is that we’ve essentially created a one class framework here. With a simple base class we manage a transaction, log execution, and provide pre- and post-execution notification. The work surrounding the meat of our implementation is both separated and consistent and doesn’t encumber the testability of our specific task classes.
We could easily add behavior to this base class (asynchronous anyone?) and make it testable through the normal means of constructor or setter dependency injection (or manual stuffing in a mock) of the services it calls on.
Additionally you could mark your Template Method (ExecuteTask) public if you don’t mind it being exposed to the world trading for increased testing ease. This is a similar choice to the whole internal/public constructor debate regarding Entity classes and, unlike The N, I won’t “Go There”.
I am sure a lot of you are probably aware of Template Method, no matter, I want to give it the love it deserves. It’s a great technique for creating simple, lo-fi frameworks that standardize, de-duplicate and separate infrastructure from pure business logic.
-
Definition? Examples? What the hell am I talking about? Click here.

GitHub
LinkedIn
Twitter
Comments on this entry are closed.