Achieving modularity
medium 45 minA module is a part of the program with a job, a small public face and a hidden inside.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Faces, insides and arrows: what a change touches.
Operations
From lump to modules
Five states of the same shop: login, catalog, cart, payment, reports, messages.
Step 1 of 5
One lump
| Shape | Cohesion | Coupling | Maintain | |
|---|---|---|---|---|
| 1 | one lump, 6 jobs | low | high | poor |
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
Six jobs in one class. Everything can touch everything.
Step 1: One lump
1 everything in one class2 group by responsibility3 give each group a face4 hide the insides5 let the build check it- Good for
- Programs that grow
- Costs
- Faces to design and keep
Words like low and high are judgements. Measure with the last twenty changes.
In the real world
The same achieving modularity doing real jobs. Pick one and step through it.
Wagons, hooks, a workshop and a closed roof.
Step 1 of 4
Hooked
Engine and three wagons.
Step 1: Hooked
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Cutting by layer at the top
majorEach feature is spread over all folders, and nothing can be private.
Wrongcontrollers/ services/ repositories/Rightauth/ orders/ products/Exporting the class
majorIts constructor and helpers become part of the promise.
Wrongexport { AuthService, TokenService } from "./internal"Rightexport type { Auth } from "./types"export { buildAuth } from "./build"Reading a neighbour's table
criticalThe schema is now public, and the owner's rules are skipped.
Wrongdb.query("select email from users where id = ?", id)Rightcustomers.address_for(customer_id)A utils module
minorHeld together by nothing, imported by all, changed by everyone.
Wrongfrom utils import send_email, parse_json, priceRightfrom pricing import quoteTrusting `__all__`
majorIt only steers
import *.Wrong__all__ = ["Auth"] # sealed?Right# plus a check in the buildassert not imports_of("auth._internal", outside="auth")Services before borders
criticalA tangle with a network in it: same ties, plus timeouts.
Wrongsplit first, find the borders laterRightmodules, own data, checks, then split one
Interview tips
Ask what it hides
- One decision per module
- No decision: no module
- Name it without 'and'
Small faces
- Ids and values
- Ask for many at once
- Own errors
Arrows
- One direction
- Checked in the build
- Ratchet for old code
Know when to stop
- Last 20 changes
- Merge borders that do not pay
- One program is fine