Composition Root

Design patterns / Clean architecture patterns
image

from typing import Protocol


# entity
class Order:
    def __init__(self, id: int, total: int):
        self.id = id
        self.total = total

    @property
    def payable(self) -> int:
        if self.total < 200:
            return self.total
        return self.total - self.total // 10


# gateway
class Catalog(Protocol):
    def price(self, sku: str) -> int | None: ...


# repository
class Orders(Protocol):
    def save(self, order: Order) -> None: ...

    def count(self) -> int: ...


# output port
class Report(Protocol):
    def say(self, text: str) -> None: ...


# use case: asks for its parts, never builds them
class PlaceOrder:
    def __init__(self, catalog: Catalog, orders: Orders,
                 report: Report):
        self._catalog = catalog
        self._orders = orders
        self._report = report
        self._next_id = 1001

    def place(self, items: dict[str, int]) -> None:
        total = 0
        for sku, count in items.items():
            price = self._catalog.price(sku)
            if price is None:
                self._report.say(f"no {sku}")
                return
            total += price * count
        order = Order(self._next_id, total)
        self._next_id += 1
        self._orders.save(order)
        self._report.say(
            f"order {order.id} for {order.payable}")


# adapters
class MemoryCatalog:
    def price(self, sku: str) -> int | None:
        return {"pen": 30, "lamp": 190}.get(sku)


class MemoryOrders:
    def __init__(self):
        self._rows: list[Order] = []

    def save(self, order: Order) -> None:
        self._rows.append(order)

    def count(self) -> int:
        return len(self._rows)


class ConsoleReport:
    def say(self, text: str) -> None:
        print(text)


class SilentReport:
    def say(self, text: str) -> None:
        pass


# composition root: the only place that sees every
# layer at once, and the only place where an adapter is
# built. the two ready builds are classmethods, because
# the root also hands out the parts it has put together
class ShopApp:
    def __init__(self, catalog: Catalog, orders: Orders,
                 report: Report):
        self.orders = orders
        self.use_case = PlaceOrder(catalog, orders, report)

    @classmethod
    def loud(cls) -> "ShopApp":
        return cls(MemoryCatalog(), MemoryOrders(),
                   ConsoleReport())

    @classmethod
    def quiet(cls) -> "ShopApp":
        return cls(MemoryCatalog(), MemoryOrders(),
                   SilentReport())


# client code
app = ShopApp.loud()
app.use_case.place({"pen": 2, "lamp": 1})
app.use_case.place({"chair": 1})
print("saved", app.orders.count())

# a second root builds the same use case differently,
# and neither the scenario nor the entity knows it
night = ShopApp.quiet()
night.use_case.place({"lamp": 1})
night.use_case.place({"pen": 2})
print("saved at night", night.orders.count())

# no adapter is built outside the root: the client
# asks for a ready application and gets one, and the
# scenario it got is the same class in both builds
print("use case", type(app.use_case).__name__)
print("same class",
      type(app.use_case) is type(night.use_case))
# printed: order 1001 for 225
#          no chair
#          saved 1
#          saved at night 2
#          use case PlaceOrder
#          same class True


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.