Composition Root

Design patterns / Clean architecture patterns
image

#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
using namespace std;

//entity
class Order {
    int id;
    int sum;

public:
    Order(int id, int sum): id(id), sum(sum) {}

    int number() const {
        return id;
    }

    int payable() const {
        return sum >= 200 ? sum - sum / 10 : sum;
    }
};

//gateway
class Catalog {
public:
    virtual ~Catalog() = default;
    virtual optional<int> price(const string& sku) = 0;
};

//repository
class Orders {
public:
    virtual ~Orders() = default;
    virtual void save(const Order& order) = 0;
    virtual int count() const = 0;
};

//output port
class Report {
public:
    virtual ~Report() = default;
    virtual void say(const string& text) = 0;
};

//use case: asks for its parts, never builds them
class PlaceOrder {
    Catalog& catalog;
    Orders& orders;
    Report& report;
    int nextId = 1001;

public:
    PlaceOrder(Catalog& c, Orders& o, Report& r)
        : catalog(c), orders(o), report(r) {}

    void place(const vector<pair<string, int>>& items) {
        int total = 0;
        for (const auto& [sku, count] : items) {
            optional<int> price = catalog.price(sku);
            if (!price) {
                report.say("no " + sku);
                return;
            }
            total += *price * count;
        }
        Order order(nextId++, total);
        orders.save(order);
        report.say("order " + to_string(order.number())
                   + " for " + to_string(order.payable()));
    }
};

//adapters
class MemoryCatalog: public Catalog {
    map<string, int> prices{{"pen", 30}, {"lamp", 190}};

public:
    optional<int> price(const string& sku) override {
        if (prices.contains(sku)) {
            return prices.at(sku);
        }
        return nullopt;
    }
};

class MemoryOrders: public Orders {
    vector<Order> rows;

public:
    void save(const Order& o) override {
        rows.push_back(o);
    }

    int count() const override { return rows.size(); }
};

class ConsoleReport: public Report {
public:
    void say(const string& text) override {
        cout << text << endl;
    }
};

class SilentReport: public Report {
public:
    void say(const string&) override {}
};

//composition root: the only place that sees every layer
//at once, and the only place where an adapter is built.
//it OWNS the adapters through unique_ptr and lends them
//to the use case as references, so the use case owns
//nothing and cannot outlive its parts. the order of the
//fields matters: the adapters are built before useCase
struct ShopApp {
    unique_ptr<Catalog> catalog;
    unique_ptr<Orders> orders;
    unique_ptr<Report> report;
    PlaceOrder useCase;

    ShopApp(unique_ptr<Catalog> c, unique_ptr<Orders> o,
            unique_ptr<Report> r)
        : catalog(std::move(c)), orders(std::move(o)),
          report(std::move(r)),
          useCase(*catalog, *orders, *report) {}

    static ShopApp loud() {
        return ShopApp(make_unique<MemoryCatalog>(),
                       make_unique<MemoryOrders>(),
                       make_unique<ConsoleReport>());
    }

    static ShopApp quiet() {
        return ShopApp(make_unique<MemoryCatalog>(),
                       make_unique<MemoryOrders>(),
                       make_unique<SilentReport>());
    }
};

//client code
ShopApp app = ShopApp::loud();
app.useCase.place({{"pen", 2}, {"lamp", 1}});
app.useCase.place({{"chair", 1}});

//a second root builds the same use case differently
ShopApp night = ShopApp::quiet();
night.useCase.place({{"lamp", 1}});
cout << "saved " << night.orders->count() << endl;
//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.