10 of 20 · 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() |
Swift example: call-site coupling vs. a feature factory
Centralizing construction means adding a dependency touches one factory instead of every caller.
Before vs. after: feature factory + validating builder
Callers pass only runtime parameters (cartID); the factory supplies shared services and returns a fresh screen every time.
// ❌ Before: every caller must hold and pass every downstream dependency.
let vc = CheckoutViewController(
viewModel: CheckoutViewModel(
cartID: id, api: api, store: store, analytics: analytics, flags: flags
)
)
// ✅ After: feature factory owns shared dependencies; callers pass only runtime input.
@MainActor
final class CheckoutFactory {
private let api: any CheckoutAPI
private let store: any CartStoring
private let analytics: any AnalyticsTracking
init(api: any CheckoutAPI, store: any CartStoring, analytics: any AnalyticsTracking) {
self.api = api
self.store = store
self.analytics = analytics
}
func makeCheckout(cartID: String) -> UIViewController {
let vm = CheckoutViewModel(cartID: cartID, api: api, store: store, analytics: analytics)
return CheckoutViewController(viewModel: vm)
}
}Keep factories focused on construction—never let a factory turn into a global service locator.
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?
- In app code I default to a struct with default values, because memberwise init plus defaults already lets callers set only what they care about.
- A builder still pays off when construction has steps or validation, when wrapping Objective-C APIs built on mutable objects, and in public frameworks that allow customization without exposing mutable properties.
- Chained calls collect settings privately and
build()returns an immutable result. - The cost is a second 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?
- The root cause is a reference type crossing a boundary while someone still mutates it.
- On iOS 15 and later I'd prefer Swift's
AttributedString, a value type, so the database gets its own copy. - Where APIs still need
NSAttributedString, I'd build into a privateNSMutableAttributedStringand havebuild()return an immutable copy. - Either way the caller can't change what it already handed off.
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.
Read it in the app's source
Done with Factory & Builder? Mark it complete. Nailing its cards builds this pumpkin, row by row.