12 of 22 · System architecture
Factory & Builder
Factories create objects so callers don't name concrete types or know their dependencies. Builders assemble an object step by step and validate once at the end.
How it's wired
- NoteScreenFactory.make(.mvvm) returns a UIViewController with its dependencies set.
- ThankYouNoteBuilder chains to/saying/with and builds a valid note or nil.
| Part | Owns | Looks like |
|---|---|---|
| Factory | Choose and assemble the concrete type | NoteScreenFactory.make(_:) |
| Builder | Stepwise construction, validate once | ThankYouNoteBuilder |
| Static factory | Named constructors | ThanksVault.onDisk(), .inMemory() |
What they buy you
- One place knows how to build a screen and what it needs, so adding a dependency doesn't ripple through every call site.
- Return a fresh instance per call to avoid shared mutable state between screens or requests.
- Static factory methods (.onDisk(), .inMemory()) name intent better than overloaded initializers.
- In Swift, default arguments and memberwise initializers replace most builders. A builder earns its place for multi-step or user-driven construction.
- A factory with one giant switch over every screen becomes a dumping ground. Split factories per feature.
When I'd use each
| Several ways to configure one type | Static factory methods. |
|---|---|
| Screens needing dependencies callers shouldn't see | A factory per feature. |
| Multi-step input such as forms or complex requests | A builder. |
Compared
Static factory vs factory type vs builder
| Static factory | Factory type | Builder | |
|---|---|---|---|
| Chooses the concrete type | Sometimes | Yes | No |
| Holds dependencies | No | Yes | Rarely |
| Validates | At the call | At the call | Once, at build() |
Expert notes
- Construction is where coupling hides. Centralize it and the rest of the code stays dumb.
Check yourself
Answer out loud before you reveal. Recall is what makes it stick.
Explain Factory & Builder in 30 seconds.
- A factory centralizes construction: callers ask for a kind of screen or object and never name the concrete type or its dependencies, so adding a dependency touches one place.
- Returning a fresh instance avoids state shared by accident.
- The risk is one giant switch that every feature edits, so I keep a factory per feature.
- Builders I keep for multi-step input, since default arguments cover the rest.
When is the Builder pattern still worth it in Swift, given structs and value types?
- Rarely in app code, because structs with default values cover most cases.
- It still pays off with Objective-C APIs where a value type isn't practical, and in public frameworks where you want customization without exposing mutable properties.
- Chained calls collect settings privately and
build()returns an immutable result. - The cost is an extra type to keep in sync.
Fast browsing builds a queue of stale requests on one shared movie loader. How do you fix the design?
- Stop sharing the loader.
- Inject a
MovieLoaderFactorythat holds the truly shared pieces, the cache and theURLSession, and give each screen its own loader. - Have the loader's
deinitcancel pending requests, so stale work dies with its screen. - View controllers pass the factory along instead of a loader.
- Share the cache, and keep request queues per screen.
A mutable attributed string is handed to the database while still being modified, causing crashes. What design prevents this?
- Accumulate into a builder that keeps the
NSMutableAttributedStringprivate, and havebuild()return an immutableNSAttributedStringcopy. - Callers never hold the mutable object, so nothing can change after handoff.
- The principle is to never let mutable state cross a boundary.
- For a public API, builders also let you close off a lot of mutable surface.
You're shipping a persistence framework. How do callers write rich queries without seeing your internal operation types?
- Give callers a builder, like
db.query(User.self).where(\.age, >, 18).sorted(by: \.name). - They chain declarative filters while your internal operation types stay private, so you can change them without breaking clients.
- Public frameworks are where builders really earn their place.
- The cost is another type to keep in sync with the internals.
The codebase has TitleLabel, SubtitleLabel and SpinnerViewController subclasses that only set properties. What do you change?
- Replace them with static factory methods, like
static func makeTitle() -> UILabel. - Setup isn't behavior, so it doesn't need a new type.
- Put the helper in a
private extensionto scope it to one file, and keep subclasses for real behavior. - The gotcha is that a static computed property can't take arguments, so it becomes a method once it needs one.
Every test builds a User with ten arguments, and a new field breaks 200 tests. What's the fix?
- Add a test-only factory, like
static func stub(permissions: [Permission] = []) -> User, with defaults for every field. - Each test passes only what it cares about, so a new field changes one stub instead of 200 call sites.
- Keep it in the test target so production can't call it.
- The name makes it obvious it's test data.