Lesson 2 of 9 · 22m
Creational Patterns: Ownership, Lifetime, and Construction
Factories, builders, singletons, and prototypes are really about who owns construction complexity and object lifetime.
Most object creation bugs are not construction bugs. They are lifetime bugs: a dependency created too early, shared too widely, or wired so deeply that tests cannot replace it. Creational patterns exist to put that ownership in one deliberate place.
Factory: hide a construction decision
Use a factory when callers need a thing, but should not decide which concrete thing they receive.
def make_notifier(settings: Settings) -> Notifier:
if settings.slack_webhook:
return SlackNotifier(settings.slack_webhook)
if settings.smtp_host:
return EmailNotifier(settings.smtp_host, settings.alert_from)
return NullNotifier()The win is not avoiding new. The win is centralizing a policy that may change: channel selection, credential lookup, retry wrapping, environment differences. If the construction never varies, the factory is ceremony.
Builder: make complex valid states constructible
Builders are valuable when construction has many optional steps and invalid combinations. A good builder accumulates intent and validates at the boundary.
const route = new RoutePlan()
.origin("ORD")
.destination("SEA")
.avoidWeather(true)
.maxLegMinutes(210)
.build(); // validates that required fields exist and constraints agreeDo not use a builder for a two-field object. Named constructor parameters or object literals already solve that problem in TypeScript, Python, Kotlin, and C#.
Singleton: usually global mutable state in a suit
Singleton is the pattern most often abused because it sounds controlled while behaving like a global variable. It makes tests order-dependent, hides dependencies, and couples unrelated subsystems through shared state.
Sometimes one instance really is required: a process-wide cache, a connection pool, a metrics registry. Even then, prefer constructing it once in main and passing it explicitly.
const cache = new RedisCache(env.REDIS_URL);
const app = createServer({ cache });The lifecycle is visible, the dependency is explicit, and a test can supply a fresh instance.
Prototype and copy construction
Prototype matters when objects are expensive to build or carry invariant-heavy configuration. Cloning a prepared template can be safer than rebuilding it, but only if copy semantics are explicit. Shallow copies of mutable nested state create the kind of bug that appears weeks later under concurrency.
Field notes
- Construction policy belongs near composition roots, not scattered through business logic.
- If every object requires a factory, your constructors are doing too much.
- Singletons are hardest to remove after they acquire hidden consumers. Treat them as a last resort, not a default.
Was this lesson helpful?