The problem is best explained with the following code:
public class TemplateClass {
public void templateOne() {
checkConditionA();
primitiveOp1();
checkConditionB();
}
public void templateTwo() {
checkConditionA();
primitiveOp2();
checkConditionB();
}
protected abstract void primitiveOp1();
protected abstract void primitiveOp2();
// rest of the methods
}
Now I have code duplication with templateOne() and templateTwo(), but I would like to have just one template method but with interchangeable primitive operations.
What you want is, in essence, a guard block around a method call. DRY programming is good practice, but be advice that you do not wawnt to couple what should not be coupled. I would only couple those two methods if it is guaranteed that they must always be guarded by the same pre- and postcondition(s).
If this is the case, I would recommend to implement a method
private void callWithChecks(Runnable primitiveOperation)and then pass the respective primitive operation as parameter to this method:If you do not want to use the function interface
Runnable, you can of course define your own interface. I went with it, since it is a Java base class.Two remarks on your code:
TempalteClassmust be declaredabstract, otherwise the code will not compilecheckConditionA()andcheckConditionB()withinTemplateClass, I would recommend defining them asprivateorfinalsuch that they cannot be overridden.