Working with Design Patterns: Template Method

Design patterns are powerful tools. Powerful tools always present the potential for misuse. If we're not careful, we could chop off a leg or glue our code together into a stick mess. Template Method is a design pattern that presents one solution for eliminating common duplication between two or more related classes. It is one of the twenty-three patterns demonstrated in the book Design Patterns (1995, by Gamma, et. al.).

You're best off treating Template Method as a refactoring goal. In this article, you'll step through an example that shows how to manipulate code to meet that goal. Instead of talking about what Template Method even is, we'll just refactor and talk about the results when we're done.

For this example, we're building a rule-based workflow system for managing scanned forms. The first rule we tackle requires that the state supplied on a form match the state passed in as an argument. The class CheckStateRule implements the Rule interface:

The workflow system executes rules. Executing a rule can move forms through the workflow.

The CheckStateRule code is fairly straightforward. The rule engine passes a Case object, a list of arguments, and a negation flag to the eval method. The Case indirectly contains form data. The switchReturnValues method, a slightly confusing bit, flips the result of the rule if someone has configured it in the workflow system to be negated.

Related Articles

As soon as we get CheckStateRule working, we begin work on a second rule, CheckDependentsRule. The job of this second rule is to ensure that each dependent specified on the form has both a first and last name.