KISS
easy 40 minKeep 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
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
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
Week 7: who cleans?
Step 1: Start
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A factory for one class
majorIt chooses between one thing, and each reader passes through it.
Wrongexporter = ExporterFactory().create("pdf") # the only oneRightexporter = PdfExporter()Simple by forgetting
criticalIt is shorter because the empty list was dropped.
Wrongreturn people[week % len(people)]Rightfor step in range(len(people)): ...return NoneClever and short
minorOne line, three ideas. The next person needs ten minutes.
Wrongx = (a and b or c)[::-1][0] if a else c[-1]Rightsource = b if a else cx = source[-1]Own code for a solved problem
majorThe pattern accepts 31 February.
Wrongre.match(r"(0[1-9]|1[0-2])/([0-2][0-9]|3[01])/", text)Rightdatetime.strptime(text, "%m/%d/%Y")One class for everything
majorFew parts, but all tied together. That is not simple.
Wrongclass Club: # rota, mail, fees, printingRightclass 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