SwiftPumpkin

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

make(.mvvm)Creates.to().saying()build()CallerWants an objectFactoryPicks + wires typeBuilderAssembles step by stepProductReturned as abstraction
calls or tellsreports backCallers never name concrete types or know the dependencies they need.
  • NoteScreenFactory.make(.mvvm) returns a UIViewController with its dependencies set.
  • ThankYouNoteBuilder chains to/saying/with and builds a valid note or nil.
PartOwnsLooks like
FactoryChoose and assemble the concrete typeNoteScreenFactory.make(_:)
BuilderStepwise construction, validate onceThankYouNoteBuilder
Static factoryNamed constructorsThanksVault.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 typeStatic factory methods.
Screens needing dependencies callers shouldn't seeA factory per feature.
Multi-step input such as forms or complex requestsA builder.

Compared

Static factory vs factory type vs builder

Static factoryFactory typeBuilder
Chooses the concrete typeSometimesYesNo
Holds dependenciesNoYesRarely
ValidatesAt the callAt the callOnce, 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.

30-second answer

Explain Factory & Builder in 30 seconds.

SwiftAsked directly

When is the Builder pattern still worth it in Swift, given structs and value types?

iOS codingAsked indirectly

Fast browsing builds a queue of stale requests on one shared movie loader. How do you fix the design?

SwiftAsked indirectly

A mutable attributed string is handed to the database while still being modified, causing crashes. What design prevents this?

System designAsked indirectly

You're shipping a persistence framework. How do callers write rich queries without seeing your internal operation types?

iOS codingAsked indirectly

The codebase has TitleLabel, SubtitleLabel and SpinnerViewController subclasses that only set properties. What do you change?

iOS codingAsked indirectly

Every test builds a User with ten arguments, and a new field breaks 200 tests. What's the fix?

Read it in the app's source