Builder
Escrito por Darjus Kazakevic · revisado el
Readable call sites, and one place that rejects bad combinations.
new Report(from, to, null, null, true, null, "csv") is hard to read: which argument is which? An options object adds names, but nothing stops an invalid mix, such as a CSV report that is also grouped.
A Builder collects the parts through named methods and creates the object in build(), the one place where the whole object is checked. In TypeScript a typed options object plus a validating function is often enough. Use a builder when parts arrive over several steps.
En esencia — Build a complex object step by step with named methods, then check the whole object in build(), so long constructors and invalid combinations go away.
Cuándo recurrir a él
Recurre a él cuando
- A constructor has many optional arguments and unreadable call sites
- Some combinations of options are invalid and must be rejected
- The object is assembled over several steps or in several places
Reconsidéralo cuando
- Three fields, all required: a constructor is clearer
- Options that never conflict: a typed options object is enough
- Test data only: a factory function with defaults is simpler
Conceptos clave
- Step methods
- Named setters that record one part and return this, so the calls chain. Each name says what the part means.
- build()
- Checks required parts and invalid combinations, then creates the object. Before build() there is no object for anyone to misuse.
- Immutable result
- The builder is the mutable part and is thrown away after build(). The object it returns should not change, so the checks stay true.
- In modern TypeScript
- A typed options object and a factory function often do the same job with less code. Required fields are enforced by the type, and the function checks combinations.
Reglas de diseño
- Validate the whole object in build()
- The chain of calls is the visible part; build() is the useful one. Check combinations there (CSV cannot be grouped), so a half-configured or contradictory object never exists.
- Return an immutable object
- The builder changes; the object it returns should not. Otherwise callers change the report after build() and skip the checks you just made.
- Prefer an options object when it is enough
- If all parts are known in one place, createReport({ range, format }) with a check inside is simpler. A builder pays off when parts are set over several steps or by several callers.
Errores habituales
- A build() that checks nothing. It is a longer constructor, not a safer one.
- Returning a mutable object, so callers change it after the checks.
- Reusing one builder for two objects, so settings from the first leak into the second.
- Writing a builder for every DTO by habit, even for three required fields.