
//entity: the rules say no with their own error type
enum OrderRule: Error {
case badCount
case emptyOrder
case orderPaid
var reason: String {
switch self {
case .badCount: return "bad count"
case .emptyOrder: return "empty order"
case .orderPaid: return "order already paid"
}
}
}
//entity
struct OrderLine {
let sku: String
let price: Int
let count: Int
//an invariant guarded where the data is born
init(sku: String, price: Int, count: Int) throws {
guard count > 0 else { throw OrderRule.badCount }
self.sku = sku
self.price = price
self.count = count
}
var cost: Int { price * count }
}
//entity
//a struct, not a class: no screen holding the order
//can change yesterday's order behind the rules' back
struct Order {
let id: Int
private(set) var lines: [OrderLine] = []
private(set) var paid = false
init(id: Int) {
self.id = id
}
var size: Int { lines.count }
var total: Int {
lines.reduce(0) { sum, line in sum + line.cost }
}
//business rule: 10% off from 200
var discount: Int {
total >= 200 ? total / 10 : 0
}
var payable: Int { total - discount }
//business rule: a paid order is closed for changes
mutating func add(_ sku: String, _ price: Int,
_ count: Int) throws {
guard !paid else { throw OrderRule.orderPaid }
lines.append(try OrderLine(sku: sku, price: price,
count: count))
}
//business rule: an empty order is never paid
mutating func pay() throws {
guard !lines.isEmpty else {
throw OrderRule.emptyOrder
}
paid = true
}
}
func refuse(_ work: () throws -> Void) {
do {
try work()
} catch let rule as OrderRule {
print("refused: \(rule.reason)")
} catch {
print("refused: \(error)")
}
}
//client code
//no database and no screen anywhere above
var order = Order(id: 1001)
try order.add("pen", 30, 2)
try order.add("lamp", 190, 1)
print("order \(order.id)")
print("lines \(order.size)")
print("total \(order.total)")
print("discount \(order.discount)")
print("payable \(order.payable)")
try order.pay()
print("paid \(order.paid)")
//a smaller order stays under the discount rule
var draft = Order(id: 1002)
try draft.add("pen", 30, 1)
print("order \(draft.id)")
print("total \(draft.total)")
print("discount \(draft.discount)")
//the rules refuse bad data, and nobody else has to
refuse { try order.add("pen", 30, 1) }
refuse { try draft.add("chair", 30, 0) }
refuse { var empty = Order(id: 1003); try empty.pay() }
//printed: order 1001
// lines 2
// total 250
// discount 25
// payable 225
// paid true
// order 1002
// total 30
// discount 0
// refused: order already paid
// refused: bad count
// refused: empty order
An entity holds a business rule of the shop and knows nothing about a database, a screen or the network, so it can be tested without them.Read moreThe problem. A shop gives 10% off every order from 200. If this rule lives in a web page, and again in a database query, the two copies soon disagree. To check the rule, you must start the page or the database. The most important knowledge of the shop is scattered and hard to test. The idea. An entity is a piece of data together with the business rules about it: what an order contains, how its total is counted, when it may be paid. It knows nothing about a database, a screen or the network. Clean architecture has one main rule, the dependency rule: outer code may know inner code, but inner code never knows outer code. Entities are the innermost code, so they depend on nothing. How to read the example. There are two entities: a line of an order and the order itself. The order sums its lines, gives 10% off from 200 and counts the amount to pay. It refuses to be paid while it is empty. The client code builds order 1001 with two lines and prints its numbers: the total is 250, the discount 25 and the amount to pay 225. It also tries to pay an empty order, and the entity refuses. In some languages the entity is a plain value with functions, not a class; its role is the same. When to use it. Make an entity for each concept of the business that has its own rules, such as an order or an account. Data without rules needs no entity: a simple structure is enough. A common mistake. An entity that saves itself to the database or formats itself for the screen. Then it depends on outer code, and its rules can no longer be tested alone. |