0

In template method pattern, we have a superclass which is defined abstract. And we have concrete classes that extend this class.

Assume that we add a new function to template method and override it in some of subclasses(only for using in some classes). We override this new method in other classes as empty(function has no body).

Does this operation count as code duplication?

enter image description here

For example, in template method we have a new function doA() (I tought to use doA() as a hook method). I want to use this function only in Class1 and between doZ() and doY().

If I add this function to template method and override this function in Class2 empty. Does this count as code duplication?

public void template(){
    doX();
    doY();
    doZ();
}

public void template(){
    doX();
    doY();
    doA();
    doZ();
}
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93
Eagle_Eye
  • 1
  • 2
  • Why do you want to override this empty and do nothing? – LostKatana Jan 05 '17 at 22:08
  • Because, methods should be called in an order – Eagle_Eye Jan 05 '17 at 22:17
  • What do you mean by order? Is that first call doX() after that call doA() and then call doZ()? Also are the methods also abstract? – LostKatana Jan 05 '17 at 22:24
  • Before adding doA() function when we call "template()", first doX(), then doY(), finally doZ() methods are operated. After adding doA() function; when client calls template() our function call order will be doX(), doY(), doA and doZ(). – Eagle_Eye Jan 05 '17 at 22:30
  • I would suggest to only mark methods that are neccessary as abstract in your Template class. If a subclass not neccessarily needs a specific method then you might write a base implementation if possible. Due to I don't know what you are trieing to achieve in your subclasses its hard to answer wheter this is redundant or not – LostKatana Jan 05 '17 at 22:43
  • @Eagle_Eye I don't see where the code duplication lies. You still have only one `template()` method in the base class, right? – guillaume31 Jan 06 '17 at 08:47

1 Answers1

0

Definitely not. You can find from the book gof23 that there are two types of methods in template method pattern:

  • abstract method, which does not have implementation body but waits for the subclass to override it
  • hook method, which is just an empty method, meaning you can just implement it in case of need, but it is not necessary
Rui
  • 3,454
  • 6
  • 37
  • 70