Composition Root

Design patterns / Clean architecture patterns
image

use std::cell::RefCell;
use std::rc::Rc;

//entity
struct Order {
    id: i64,
    total: i64,
}

impl Order {
    fn payable(&self) -> i64 {
        if self.total >= 200 {
            self.total - self.total / 10
        } else {
            self.total
        }
    }
}

//gateway
trait Catalog {
    fn price(&self, sku: &str) -> Option<i64>;
}

//repository
trait Orders {
    fn save(&self, order: Order);
    fn count(&self) -> usize;
}

//output port
trait Report {
    fn say(&self, text: &str);
}

//use case: asks for its parts, never builds them
struct PlaceOrder {
    catalog: Box<dyn Catalog>,
    orders: Rc<dyn Orders>,
    report: Box<dyn Report>,
    next_id: i64,
}

impl PlaceOrder {
    fn place(&mut self, items: &[(&str, i64)]) {
        let mut total = 0;
        for (sku, count) in items {
            match self.catalog.price(sku) {
                Some(price) => total += price * count,
                None => {
                    self.report.say(&format!("no {}", sku));
                    return;
                }
            }
        }
        let order = Order {
            id: self.next_id,
            total,
        };
        self.next_id += 1;
        let text = format!("order {} for {}",
                           order.id, order.payable());
        self.orders.save(order);
        self.report.say(&text);
    }
}

//adapters
struct MemoryCatalog;

impl Catalog for MemoryCatalog {
    fn price(&self, sku: &str) -> Option<i64> {
        [("pen", 30), ("lamp", 190)].iter()
            .find(|(name, _)| *name == sku)
            .map(|(_, price)| *price)
    }
}

struct MemoryOrders {
    rows: RefCell<Vec<Order>>,
}

impl Orders for MemoryOrders {
    fn save(&self, order: Order) {
        self.rows.borrow_mut().push(order);
    }

    fn count(&self) -> usize {
        self.rows.borrow().len()
    }
}

struct ConsoleReport;

impl Report for ConsoleReport {
    fn say(&self, text: &str) {
        println!("{}", text);
    }
}

struct SilentReport;

impl Report for SilentReport {
    fn say(&self, _text: &str) {}
}

//composition root: the only place that sees every layer
//at once, and the only place where an adapter is built.
//in Rust it is also where ownership is settled: the
//catalog and the report are MOVED into the use case as
//Box, while the store is SHARED with the root as Rc
struct ShopApp {
    use_case: PlaceOrder,
    orders: Rc<dyn Orders>,
}

impl ShopApp {
    fn build(report: Box<dyn Report>) -> ShopApp {
        let orders: Rc<dyn Orders> = Rc::new(MemoryOrders {
            rows: RefCell::new(Vec::new()),
        });
        ShopApp {
            use_case: PlaceOrder {
                catalog: Box::new(MemoryCatalog),
                orders: orders.clone(),
                report,
                next_id: 1001,
            },
            orders,
        }
    }

    fn loud() -> ShopApp {
        ShopApp::build(Box::new(ConsoleReport))
    }

    fn quiet() -> ShopApp {
        ShopApp::build(Box::new(SilentReport))
    }
}

//client code
let mut app = ShopApp::loud();
app.use_case.place(&[("pen", 2), ("lamp", 1)]);
app.use_case.place(&[("chair", 1)]);

//a second root builds the same use case differently
let mut night = ShopApp::quiet();
night.use_case.place(&[("lamp", 1)]);
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 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.