
//entity
struct Order {
let id: Int
let total: Int
var payable: Int {
total >= 200 ? total - total / 10 : total
}
}
//gateway
protocol Catalog {
func price(_ sku: String) -> Int?
}
//repository
protocol Orders {
func save(_ order: Order)
var count: Int { get }
}
//output port
protocol Report {
func say(_ text: String)
}
//use case: asks for its parts, never builds them
final class PlaceOrder {
private let catalog: any Catalog
private let orders: any Orders
private let report: any Report
private var nextId = 1001
init(catalog: any Catalog, orders: any Orders,
report: any Report) {
self.catalog = catalog
self.orders = orders
self.report = report
}
func place(_ items: [(sku: String, count: Int)]) {
var total = 0
for item in items {
guard let price = catalog.price(item.sku) else {
report.say("no \(item.sku)")
return
}
total += price * item.count
}
let order = Order(id: nextId, total: total)
nextId += 1
orders.save(order)
report.say("order \(order.id)"
+ " for \(order.payable)")
}
}
//adapter
struct MemoryCatalog: Catalog {
private let prices = ["pen": 30, "lamp": 190]
func price(_ sku: String) -> Int? {
prices[sku]
}
}
//adapter
final class MemoryOrders: Orders {
private var rows: [Order] = []
func save(_ order: Order) {
rows.append(order)
}
var count: Int { rows.count }
}
//adapter
struct ConsoleReport: Report {
func say(_ text: String) {
print(text)
}
}
//adapter
struct SilentReport: Report {
func say(_ text: String) {
}
}
//composition root: the only place that sees every layer
//at once, and the only place where an adapter is built
//the default values in the init are the whole container
//this shop needs: a caller names only what it wants to
//be different, and a default is built anew every call
struct ShopApp {
let useCase: PlaceOrder
let orders: any Orders
init(catalog: any Catalog = MemoryCatalog(),
orders: any Orders = MemoryOrders(),
report: any Report = ConsoleReport()) {
self.orders = orders
self.useCase = PlaceOrder(catalog: catalog,
orders: orders,
report: report)
}
static func loud() -> ShopApp {
ShopApp()
}
static func quiet() -> ShopApp {
ShopApp(report: SilentReport())
}
}
//client code
let app = ShopApp.loud()
app.useCase.place([(sku: "pen", count: 2),
(sku: "lamp", count: 1)])
app.useCase.place([(sku: "chair", count: 1)])
//a second root builds the same use case differently
let night = ShopApp.quiet()
night.useCase.place([(sku: "lamp", count: 1)])
print("saved \(night.orders.count)")
//printed: order 1001 for 225
// no chair
// saved 1
A composition root is the only place where the layers are connected and the adapters are built; the rest of the application only asks for its parts.Read moreThe problem. A use case needs a catalogue of prices, a store for orders and a way to report. If the use case creates these parts itself, it names adapters of the outer layer and depends on them. A test cannot give it other parts. If every part of the program builds its own parts, nobody sees how the application is connected. The idea. A composition root is the only place where the layers are connected and the adapters are built. An adapter is outer code that implements a port, the interface that the inner layer declares. The use case only asks for its parts through ports and never builds them. The root knows every layer at once, and that is its job. All other code keeps the dependency rule: inner code never knows outer code. No framework or container is needed: the root is plain code at the start of the program. How to read the example. The use case asks for three ports: a gateway for prices, a repository for orders and an output port for reports. The outer layer has adapters for them: a catalogue and a store in memory, a report that prints and a report that says nothing. The example builds the application twice. In the first build the report prints: the client code places order 1001, with 225 to pay, and an order for an unknown item. The second build has the silent report, so its orders print nothing. Only the count of saved orders shows that they were saved. The use case is the same in both builds. When to use it. Every application has one composition root, at its start; a test may have its own small root with fake adapters. A short script without ports needs no root. A common mistake. Creating an adapter inside a use case, even once. The use case then depends on the outer layer, and the root no longer shows how the application is connected. |