AlgoViz

KISS

easy 40 min

Keep it simple: choose the design with the fewest parts that still does the whole job, edge cases included.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:27

See it run

Objects at run time: which parts do work, which only pass it on, and where the edges are handled.

Operations

Hello, the long way

One greeting through four objects. Count the files that a reader opens.

Step 1 of 5

A caller

maincallerfiles opened1

It wants one text.

Step 1: A caller

class FormalGreeting:    def greet(self, name): return "Hello, " + nameclass GreetingFactory:    def create(self, kind): return {"formal": FormalGreeting}[kind]()class GreetingService:    def __init__(self, factory): self.factory = factory    def say_hello(self, name): return self.factory.create("formal").greet(name)print(GreetingService(GreetingFactory()).say_hello("World"))
Good for
Many kinds of greeting
Costs
Three hops without work
Lines that do the work
1

Point at each class and name the requirement. No name, no class.

In the real world

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

A web page wants one name. Four stops, one of them works.

Step 1 of 6

Start

web pagestartwantsa namemanagerRotaManageradds?configRotaConfigadds?factoryStrategyFactoryadds?round robinRoundRobinadds?

Week 7: who cleans?

Step 1: Start

Common mistakes

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

  • A factory for one class

    major

    It chooses between one thing, and each reader passes through it.

    Wrong
    exporter = ExporterFactory().create("pdf")   # the only one
    Right
    exporter = PdfExporter()
  • Simple by forgetting

    critical

    It is shorter because the empty list was dropped.

    Wrong
    return people[week % len(people)]
    Right
    for step in range(len(people)): ...return None
  • Clever and short

    minor

    One line, three ideas. The next person needs ten minutes.

    Wrong
    x = (a and b or c)[::-1][0] if a else c[-1]
    Right
    source = b if a else cx = source[-1]
  • Own code for a solved problem

    major

    The pattern accepts 31 February.

    Wrong
    re.match(r"(0[1-9]|1[0-2])/([0-2][0-9]|3[01])/", text)
    Right
    datetime.strptime(text, "%m/%d/%Y")
  • One class for everything

    major

    Few parts, but all tied together. That is not simple.

    Wrong
    class Club:   # rota, mail, fees, printing
    Right
    class Rota: ...def lines(rows): ...

Interview tips

  • One sentence

    • Say the job first
    • Say what the code does
    • If they differ, simplify
  • Each part has an owner

    • Point at a class
    • Name the requirement
    • None: remove it
  • Plain plus trigger

    • Build the plain design
    • Tell its limit
    • Tell the next step
  • Keep the rim

    • Empty, wrong, twice
    • Failures have one meaning
    • Say the gap that stays