Builder
medium 50 minThe Builder collects the parts of a complex object one by one, checks them together, and creates the object in a single moment.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Watch the changeable builder fill up, and the fixed product appear in one moment.
Operations
Burger, step by step
Sesame bun, beef, cheddar, tomato, lettuce. Then build.
Step 1 of 8
Create the builder
Empty, and that is fine. Nobody can eat a builder.
Step 1: Create the builder
class BurgerBuilder: def set_bun(self, bun): self._bun = bun return self def set_patty(self, patty): self._patty = patty return self def set_cheese(self, cheese): self._cheese = cheese return self def add_topping(self, topping): self._toppings.append(topping) return self def build(self): if self._bun is None or self._patty is None: raise ValueError("missing part") return Burger(self._bun, self._patty, self._cheese, tuple(self._toppings))- Watch
- The fields of the builder
- Result
- One fixed burger
Until the last step there is no burger at all.
In the real world
The same builder doing real jobs. Pick one and step through it.
Two requests at the same moment, one shared builder.
Step 1 of 4
A field
Somebody stored the builder in the service to save an object.
Step 1: A field
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No copy in build
criticalA finished product changes later.
Wrongreturn Order(self._items)Rightreturn Order(tuple(self._items))A step that forgets to return
majorThe chain breaks at the next dot.
Wrongdef set_bun(self, bun): self._bun = bunRightdef set_bun(self, bun): self._bun = bun return selfRules that depend on the order
majormethod before body fails, body before method works.
Wrongdef method(self, m): if m == "POST" and self._body is None: raise ValueErrorRightdef build(self): if self._method == "POST" and self._body is None: raise ValueErrorRecipe without reset
criticalThe second burger inherits the pickles of the first.
Wrongdef minimal(self): return self._b.set_bun("Plain").build()Rightdef minimal(self): return self._b.reset().set_bun("Plain").build()Builder as a shared field
criticalTwo requests mix their choices.
Wrongself._builder = RequestBuilder()Rightdef send(self, url): request = RequestBuilder().url(url).build()Values pasted into SQL
criticalInjection with a pleasant interface.
Wrongq.where("name = '" + name + "'")Rightq.where("name", "=", name)
Interview tips
Draw the border
- Left of build: changeable.
- Right of build: fixed.
- One door between them.
Name the steps
- Set replaces.
- Add collects.
- Build creates.
Place the rules
- One value: in the step.
- Between parts: in build.
- The world: in the service.
Say the contract
- One shot or reusable?
- Copy or move?
- One thread.
Know when to stop
- Named arguments first.
- Director only for recipes.
- Interface only for two builders.