AlgoViz

Factory method

medium 60 min

A fixed workflow with one open step that creates an object.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:53

See it run

One workflow, one open line, and who fills it.

Operations

Two branches

The same recipe runs in two branches. Only the mould differs.

Step 1 of 6

An order

leeCustomerhillHillBranchmake()

Lee asks the hill branch for a candle. make is inherited.

Step 1: An order

class Workshop(ABC):    def make(self):        candle = self.take_mould()        return finish(candle)    @abstractmethod    def take_mould(self): ...class HillBranch(Workshop):    def take_mould(self): return Pillar()class HarbourBranch(Workshop):    def take_mould(self): return Floating()
Watch
The call to itself
Result
Two kinds, one recipe

The base class calls a method that it does not have.

In the real world

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

A factory opens a connection, then the login fails. Who closes it?

Step 1 of 4

Open

factoryPoolFactoryconnectionConnectionopenyesopen

The factory opens a connection.

Step 1: Open

Common mistakes

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

  • A default nobody ordered

    critical

    A typing mistake produces the wrong product without an error.

    Wrong
    if kind == "sms": return Sms()return Email()
    Right
    if kind == "sms": return Sms()raise UnknownKind(kind)
  • Casting the product back

    major

    The caller depends on the class again, and breaks with the next one.

    Wrong
    vehicle = factory.create_vehicle()if isinstance(vehicle, BmwM5): ...
    Right
    vehicle = factory.create_vehicle()vehicle.drive()
  • Calling it in the base constructor

    critical

    The override runs before its own fields exist.

    Wrong
    def __init__(self):    self.button = self.create_button()
    Right
    def button(self):    if self._button is None:        self._button = self.create_button()    return self._button
  • A subclass for a number

    major

    Fifteen classes that differ in two integers.

    Wrong
    class Candle40(Workshop):    def take_mould(self): return Pillar(40)
    Right
    Workshop(make=lambda: Pillar(40))
  • Leaking on failure

    critical

    The caller never got a reference, so it can not close it.

    Wrong
    c = Connection(name)c.login(secret)return c
    Right
    c = Connection(name)try: c.login(secret)except BaseException: c.close(); raisereturn c
  • Class names from outside

    critical

    Text from a request chooses which code runs.

    Wrong
    return globals()[request.kind]()
    Right
    return registry.create(request.kind)

Interview tips

  • Look for the workflow

    • Same steps, one gap.
    • Then it is this pattern.
    • No workflow: a function.
  • Return the interface

    • Callers know Vehicle.
    • No casts.
    • New or shared: say it.
  • Count the classes

    • Parallel trees hurt.
    • Pass a function instead.
    • Data is a parameter.
  • Somebody chooses

    • Choose in main.
    • Unknown is an error.
    • Seal the registry.