1

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.

Horyzon
  • 33
  • 3

1 Answers1

2

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:

public abstract class TemplateClass {
    public void templateOne() {
        callWithChecks(this::primitiveOp1);
    }

    public void templateTwo() {
        callWithChecks(this::primitiveOp2);
    }

    private void callWithCkecks(Runnable primitiveOperation) {
        checkConditionA();
        primitiveOperation.run();
        checkConditionB();
    }

    protected abstract void primitiveOp1();
    protected abstract void primitiveOp2();
    // rest of the methods
}

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:

  • TempalteClass must be declared abstract, otherwise the code will not compile
  • If you intend to implement methods checkConditionA() and checkConditionB() within TemplateClass, I would recommend defining them as private or final such that they cannot be overridden.
Turing85
  • 18,217
  • 7
  • 33
  • 58