DRY
easy 40 minDon't repeat yourself: every piece of knowledge has one home, and everything else asks that home.
Watch lesson4:18
One source, many outputs
When copies must exist, let a machine make them.
The point: a generated copy is fine if nobody edits it and a test notices when it is old.
The limits of a member record are needed in the program, in the database and on the help page. Three languages, so three texts. One table of fields can drive all of them.
One schema, three outputs
1/4The source
A schema is a list of fields with limits. Only this is edited by people.
owns (dies together)uses
A schema that writes its copies
The facts are data. The validator contains no limit of its own.
from dataclasses import dataclassfrom hashlib import sha256@dataclass(frozen=True)class Field: name: str kind: str # "text" counts characters, "int" is the value low: int high: intMEMBER = (Field("name", "text", 1, 40), Field("age", "int", 0, 130))def check(fields, data): errors = [] for f in fields: value = data.get(f.name) wanted = str if f.kind == "text" else int if type(value) is not wanted: errors.append(f"{f.name}: expected {f.kind}") continue size = len(value) if f.kind == "text" else value if not f.low <= size <= f.high: errors.append(f"{f.name}: must be {f.low} to {f.high}") return errorsLines 5 to 10
Four facts per field. Nothing here knows about SQL or help pages.
1 of 4
Why it is built this way
- Run-time reading is the best kind of sharing: there is nothing that can be old.