Composition Root

Design patterns / Clean architecture patterns
image

//a port method with no body names the class that left
//it out: JavaScript has no interfaces, so a port here
//is a base class and extends says who serves it
function notWritten(owner, method) {
    throw new Error(owner.constructor.name + "." + method);
}

//entity
class Order {
    #total;

    constructor(id, total) {
        this.id = id;
        this.#total = total;
    }

    payable() {
        let cut = this.#total >= 200 ? this.#total / 10 : 0;
        return this.#total - Math.trunc(cut);
    }
}

//gateway
class Catalog {
    price(sku) {
        notWritten(this, "price");
    }
}

//repository
class Orders {
    save(order) {
        notWritten(this, "save");
    }

    count() {
        notWritten(this, "count");
    }
}

//output port
class Report {
    say(text) {
        notWritten(this, "say");
    }
}

//use case: asks for its parts, never builds them
class PlaceOrder {
    #catalog;
    #orders;
    #report;
    #nextId = 1001;

    constructor(catalog, orders, report) {
        this.#catalog = catalog;
        this.#orders = orders;
        this.#report = report;
    }

    place(items) {
        let total = 0;
        for (let [sku, count] of items) {
            let price = this.#catalog.price(sku);
            if (price === undefined) {
                this.#report.say("no " + sku);
                return;
            }
            total += price * count;
        }
        let order = new Order(this.#nextId++, total);
        this.#orders.save(order);
        this.#report.say("order " + order.id +
            " for " + order.payable());
    }
}

//adapters
class MemoryCatalog extends Catalog {
    #prices = new Map([["pen", 30], ["lamp", 190]]);

    price(sku) {
        return this.#prices.get(sku);
    }
}

class MemoryOrders extends Orders {
    #rows = new Map();

    save(order) {
        this.#rows.set(order.id, order);
    }

    count() {
        return this.#rows.size;
    }
}

class ConsoleReport extends Report {
    say(text) {
        console.log(text);
    }
}

class SilentReport extends Report {
    say(text) {
    }
}

//composition root: the only place that sees every layer
//at once, and the only place where new stands next to an
//adapter. No container is needed; a function is the root
function build(report) {
    let orders = new MemoryOrders();
    return {
        useCase: new PlaceOrder(
            new MemoryCatalog(), orders, report),
        orders: orders
    };
}

function loud() {
    return build(new ConsoleReport());
}

function quiet() {
    return build(new SilentReport());
}

//client code
let app = loud();
app.useCase.place(new Map([["pen", 2], ["lamp", 1]]));
app.useCase.place(new Map([["chair", 1]]));

//a second root builds the same use case differently, and
//neither of them ever named a class inside the use case
let night = quiet();
night.useCase.place(new Map([["lamp", 1]]));
console.log("night saved " + night.orders.count());
console.log("loud saved " + app.orders.count());
//printed: order 1001 for 225
//         no chair
//         night saved 1
//         loud 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.