
import "fmt"
//entity
type Order struct {
ID int
Total int
}
func (o Order) Payable() int {
if o.Total >= 200 {
return o.Total - o.Total/10
}
return o.Total
}
//gateway
type Catalog interface {
Price(sku string) (int, bool)
}
//repository
type Orders interface {
Save(order Order)
Count() int
}
//output port
type Report interface {
Say(text string)
}
type Item struct {
SKU string
Count int
}
//use case: asks for its parts, never builds them
type PlaceOrder struct {
catalog Catalog
orders Orders
report Report
nextID int
}
func (u *PlaceOrder) Place(items []Item) {
total := 0
for _, item := range items {
price, ok := u.catalog.Price(item.SKU)
if !ok {
u.report.Say("no " + item.SKU)
return
}
total += price * item.Count
}
order := Order{u.nextID, total}
u.nextID++
u.orders.Save(order)
u.report.Say(fmt.Sprintf("order %d for %d",
order.ID, order.Payable()))
}
//adapters
type MemoryCatalog struct{}
func (MemoryCatalog) Price(sku string) (int, bool) {
prices := map[string]int{"pen": 30, "lamp": 190}
price, ok := prices[sku]
return price, ok
}
type MemoryOrders struct {
rows []Order
}
func (m *MemoryOrders) Save(order Order) {
m.rows = append(m.rows, order)
}
func (m *MemoryOrders) Count() int {
return len(m.rows)
}
type ConsoleReport struct{}
func (ConsoleReport) Say(text string) {
fmt.Println(text)
}
type SilentReport struct{}
func (SilentReport) Say(text string) {
}
//composition root: the only place that sees every layer
//at once, and the only place where an adapter is built.
//go has no container for this on purpose: wiring is
//plain code, and in a real program it lives in main
type ShopApp struct {
UseCase *PlaceOrder
Orders Orders
}
func newApp(report Report) *ShopApp {
orders := &MemoryOrders{}
return &ShopApp{
UseCase: &PlaceOrder{MemoryCatalog{}, orders,
report, 1001},
Orders: orders,
}
}
func newLoudApp() *ShopApp {
return newApp(ConsoleReport{})
}
func newQuietApp() *ShopApp {
return newApp(SilentReport{})
}
//client code
app := newLoudApp()
app.UseCase.Place([]Item{{"pen", 2}, {"lamp", 1}})
app.UseCase.Place([]Item{{"chair", 1}})
//a second root builds the same use case differently
night := newQuietApp()
night.UseCase.Place([]Item{{"lamp", 1}})
fmt.Println("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. |