AlgoViz

Template method pattern

medium 50 min

Template method writes the order of an algorithm once, in a base class, and leaves some steps open for subclasses.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:38

See it run

One object, two halves: the base part keeps the order, the own part fills the gaps.

Operations

Making tea

Follow the order. Blue calls go to the half that has the step.

Step 1 of 7

An order

baristaBaristabase partBeverageMakersteps0lastnoneown partTeaprepare_recipe()

The barista calls the one public method. They do not say how tea is made.

Step 1: An order

def prepare_recipe(self):    self._boil_water()    self._brew()    self._pour_in_cup()    if self._wants_condiments():        self._add_condiments()
Watch
Who answers
Result
Four steps

The own part never calls. It is called.

In the real world

The same template method doing real jobs. Pick one and step through it.

Bread, filling, toppings, wrap.

Step 1 of 3

BLT

guestGuestbase partSandwichsteps6own partBlttoppingmayo_filling()3 things

Filling: bacon, lettuce, tomato. Toppings: mayonnaise.

Step 1: BLT

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • The order can be overridden

    critical

    One subclass writes its own order and misses every later rule.

    Wrong
    class Espresso(BeverageMaker):    def prepare_recipe(self):        self._brew()
    Right
    class BeverageMaker(ABC):    @final    def prepare_recipe(self): ...
  • An open step in the constructor

    critical

    The subclass is not built yet.

    Wrong
    def __init__(self):    self.title = self._make_title()
    Right
    def __init__(self, title):    self.title = title
  • Please call super

    major

    Somebody forgets, and nothing complains.

    Wrong
    def open(self):    super().open()   # do not forget!
    Right
    def open(self):      # final    self._track()    self._on_open()  # empty hook
  • An empty body instead of abstract

    major

    A drink without brewing is served as hot water.

    Wrong
    def _brew(self):    pass
    Right
    @abstractmethoddef _brew(self): ...
  • Cleanup as the last line

    critical

    A step that raises skips it.

    Wrong
    rows = self._parse(source)self._close(source)
    Right
    try:    rows = self._parse(source)finally:    self._close(source)
  • Asking for the class in the skeleton

    major

    The base class knows its children.

    Wrong
    if isinstance(self, Coffee):    self._ask()
    Right
    if self._wants_condiments():    self._add_condiments()

Interview tips

  • Find the rows

    • Variants side by side.
    • Equal: fixed.
    • Different: abstract.
    • Mostly equal: hook.
  • Lock what matters

    • Template final.
    • Fixed steps private.
    • Steps protected.
  • Keep steps innocent

    • Arguments in.
    • Results out.
    • Nothing to remember.
  • Know the exit

    • Two steps vary?
    • Inject them.
    • Keep the skeleton.