Composition Root

Design patterns / Clean architecture patterns
image

;; Composition root folds into one function that builds
;; the adapters and hands them to the use case: no
;; container, only arguments

;; Entity
(defn payable [order]
  (let [total (:total order)]
    (if (>= total 200)
      (- total (quot total 10))
      total)))

;; Gateway
(defprotocol Catalog
  (price [catalog sku]))

;; Repository: it numbers what it saves
(defprotocol Orders
  (save [orders order])
  (saved [orders]))

;; Output port
(defprotocol Report
  (say [report text]))

;; Use case: asks for its parts, never builds them
(defn place-order [catalog orders report]
  (fn [items]
    (if-let [sku (first (remove #(price catalog %)
                                (keys items)))]
      (say report (str "no " sku))
      (let [total (reduce + 0
                          (for [[sku qty] items]
                            (* (price catalog sku) qty)))
            order (save orders {:total total})]
        (say report (str "order " (:id order)
                         " for " (payable order)))))))

;; Adapters
(defrecord MemoryCatalog [prices]
  Catalog
  (price [_ sku]
    (get prices sku)))

(defrecord MemoryOrders [rows]
  Orders
  (save [_ order]
    (peek (swap! rows
                 (fn [kept]
                   (conj kept
                         (assoc order :id
                                (+ 1001 (count kept))))))))
  (saved [_]
    (count @rows)))

(def console-report
  (reify Report
    (say [_ text]
      (println text))))

(def silent-report
  (reify Report
    (say [_ _])))

;; Composition root: the only place that sees every
;; layer at once, and the only place that names an
;; adapter. The app it returns is a plain map
(defn shop-app [report]
  (let [orders (->MemoryOrders (atom []))]
    {:place (place-order
              (->MemoryCatalog {"pen" 30 "lamp" 190})
              orders
              report)
     :orders orders}))

(defn loud [] (shop-app console-report))
(defn quiet [] (shop-app silent-report))

;; Client code
(def app (loud))
((:place app) {"pen" 2 "lamp" 1})
((:place app) {"chair" 1})

;; A second root builds the same use case differently
(def night (quiet))
((:place night) {"lamp" 1})
(println "saved" (saved (:orders night)))
;; 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 more

The 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.