12 of 20 · System architecture
Decoupled Layers
Decoupled layers organize code so dependencies point inward: the UI and data layers depend on the domain, and the domain (models, rules and protocols, or ports) depends on nothing.
How it's wired
- PumpkinDomain defines entities and ports.
- PumpkinStorage and PumpkinRPC implement them. The app only talks to ports.
| Part | Owns | Looks like |
|---|---|---|
| Domain | Entities, rules, protocols (ports) | PumpkinDomain |
| Data | Adapters implementing ports | PumpkinStorage, PumpkinRPC |
| UI | Screens talking to ports only | App target |
Swift example: leaked Core Data type vs. mapped domain boundary
Passing an NSManagedObject into a ViewModel ties UI code to Core Data's thread-confined context.
Before vs. after: map storage records at the data boundary
Domain structs are plain Sendable values; Core Data or SQLite stays isolated inside the data adapter.
// ❌ Before: Core Data leaks into presentation (non-Sendable, crashes off-queue).
final class LeakyNotesVM {
var entities: [NoteManagedObject] = [] // tied to NSManagedObjectContext!
}
// ✅ After: Domain defines plain Sendable types + ports; Data maps at the boundary.
struct Note: Sendable, Identifiable {
let id: UUID
let body: String
}
protocol NoteRepository: Sendable {
func fetchNotes() async throws -> [Note]
}
final class CoreDataNoteRepository: NoteRepository {
private let context: NSManagedObjectContext
init(context: NSManagedObjectContext) { self.context = context }
func fetchNotes() async throws -> [Note] {
try await context.perform {
// Map NSManagedObject -> plain Sendable Note before crossing the boundary.
try self.context.fetch(NoteManagedObject.fetchRequest()).map {
Note(id: $0.id, body: $0.body)
}
}
}
}For large tables, paginate or window queries at the repository boundary rather than eagerly mapping thousands of rows.
How to tell the layers are real
- The swap test: could you replace disk storage with CloudKit without touching a view? If not, a layer leaked.
- Map at the boundary. The data layer converts DTOs and managed objects into domain structs. A Core Data type inside a ViewModel is a leak.
- Enforce with modules, not folders. A Swift package per layer makes an illegal import fail to compile.
- Don't over-layer. Every boundary costs mapping code. A two-screen app needs folders, not five packages.
When I'd layer formally
| Apps expected to outlive their backend or UI framework | Domain package plus adapters. |
|---|---|
| Several teams sharing models and rules | A domain module everyone depends on. |
| Prototypes | Folders. Formal layers come later. |
Expert notes
- Layers aren't about neatness. They decide what you can change without fear.
Check yourself
Answer out loud before you reveal. Recall is what makes it stick.
Explain Decoupled Layers in 30 seconds.
- Decoupled layers point every dependency inward: the UI and data layers depend on the domain, and the domain (models, rules and protocols) depends on nothing.
- Adapters convert DTOs and database objects into domain types at the boundary.
- My test: could I swap disk storage for CloudKit without touching a view?
- The cost is mapping code at every boundary, so I don't formalize layers for a two-screen app.
State the dependency rule. How does a use case call out to a presenter without breaking it?
- Source dependencies point inward only, so inner layers never name outer types, including UIKit or Core Data.
- When a use case must push results out, it calls a protocol it owns, like
protocol OrderOutput { func present(_ orders: [Order]) }, and the presenter conforms. - Control flows out while the import still points in.
- In an MVVM feature I'd usually skip the output protocol, because the use case can return values and the view model publishes the state.
The domain layer passes Core Data managed objects straight up to views. What's the risk, and the fix?
- Map them to plain structs at the boundary.
- Passing
NSManagedObjectupward couples every layer to Core Data, so views inherit its threading rules, faults and schema changes. - Data crossing a boundary should be simple values shaped for the inner layer.
- The mapping code is boring, but it's what lets you change persistence later without touching views.
The same business rules must power iPhone, iPad and Mac apps. How do you layer the code?
- I'd keep business rules in plain Swift types with no UIKit or AppKit import, in a shared module, so all three apps compile the same logic and test it once.
- View models can often be shared too, since SwiftUI runs on all three.
- I'd split views where layout and input differ, like sidebars and menu commands on Mac, and keep persistence behind a store protocol.
- The risk is forcing one view hierarchy onto every platform, which makes the Mac app feel like a port.
Rules like whether a user can comment are copied across view controllers and a global helper. Where should they live?
- I'd give the rule one home: a small viewless type that owns the model and exposes purpose-built answers, like
var canComment: Bool. - View controllers ask it instead of recomputing, and the global helper goes away, so the rule has one tested code path.
- I wouldn't put it on the plain model struct if it needs services or the session.
- I'd avoid a global too, because that drags in shared mutable state.
- The cost is an API per use case.
Read it in the app's source
Done with Decoupled Layers? Mark it complete. Nailing its cards builds this pumpkin, row by row.