I Heart Template Method

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.

Comments (5) left to “I Heart Template Method”

  1. Evan wrote:

    one tiny suggestion for this object, instead of building the “one object to rule them all” base class, you could do the following:

    create an interface IExecutable with one method, Execute()

    then build a class for each technical concern (logging, transactions, security, eventing aka observation, caching)..

    each of the classes can implement IExecutable and take another IExecutable in their constructor..it’s a simple way to layer each on top while keeping true to the single responsibility and open/closed principles..each class performs its responsibility and then delegates to the next object (passed into the constructor) until the final object gets executed (the real Task object).. it gives you the freedom to change one technical concern without affecting the others..or providing multiple implementations of a particular concern (ie..two caching modes). you can also apply some concerns to some tasks while leaving others off (or rearranging the order of execution).. you can think of them as mini-layers on top of your task object (which also implements IExecutable)

    you can either wire the whole thing up with a DI container or create a factory to add the objects onto the task objects (depending on the app)

  2. Jeffrey Palermo wrote:

    I share the love for the Template method. With inheritence hierarchies I find myself using it ALL the time.

  3. Dave wrote:

    Yeah, it’s pretty handy.

    I have a new and very long post coming out today on how to get implement a POCO template method using generics in response to Evan’s comment above about violating SRP/OCP. I’d be interested in your feedback on that.

  4. Evan wrote:

    another interesting tidbit i picked up while reading Pugh’s Interface Oriented Programming..

    it’s easier to refactor into an inheritance hierarchy from interfaces than to refactor to interfaces from an inheritance hierarchy..

    i’m slowly becoming less and less of a fan of layer supertypes..

    the other thing that jumped out at me was that interfaces represent a CAN DO relationship (which popped on a light bulb for me).. shortly thereafter i refactored the security roles and permissions of our app to support a new interface IAssertable.. ;-)

  5. the ‘bee log / Refactoring My Template Method Post wrote:

    […] I Heart Template Method […]

Post a Comment

*Required
*Required (Never published)