
constexpr size_t maxOrders = 8;
//entity
typedef struct {
int id;
int sum;
} Order;
int orderPayable(const Order *order) {
int sum = order->sum;
return sum >= 200 ? sum - sum / 10 : sum;
}
//gateway
typedef struct Catalog {
bool (*price)(struct Catalog *self, const char *sku,
int *price);
} Catalog;
//repository
typedef struct Orders {
bool (*save)(struct Orders *self, const Order *order);
size_t (*count)(struct Orders *self);
} Orders;
//output port
typedef struct Report {
void (*say)(struct Report *self, const char *text);
} Report;
typedef struct {
const char *sku;
int count;
} Item;
//use case: asks for its parts, never builds them
typedef struct {
Catalog *catalog;
Orders *orders;
Report *report;
int nextId;
} PlaceOrder;
void placeOrder(PlaceOrder *useCase, const Item items[],
size_t count) {
Catalog *catalog = useCase->catalog;
Report *report = useCase->report;
char text[32];
int total = 0;
for (size_t i = 0; i < count; i++) {
const Item *item = &items[i];
int price = 0;
if (!catalog->price(catalog, item->sku, &price)) {
snprintf(text, sizeof text, "no %s", item->sku);
report->say(report, text);
return;
}
total += price * item->count;
}
Order order = {useCase->nextId, total};
if (!useCase->orders->save(useCase->orders, &order)) {
report->say(report, "not saved");
return;
}
useCase->nextId++;
snprintf(text, sizeof text, "order %d for %d", order.id,
orderPayable(&order));
report->say(report, text);
}
//adapters
bool memoryPrice(Catalog *, const char *sku, int *price) {
static const struct {
const char *sku;
int price;
} prices[] = {{"pen", 30}, {"lamp", 190}};
size_t count = sizeof prices / sizeof prices[0];
for (size_t i = 0; i < count; i++) {
if (strcmp(prices[i].sku, sku) == 0) {
*price = prices[i].price;
return true;
}
}
return false;
}
typedef struct {
Orders base;
Order rows[maxOrders];
size_t size;
} MemoryOrders;
bool memorySave(Orders *self, const Order *order) {
MemoryOrders *memory = (MemoryOrders *)self;
if (memory->size == maxOrders) {
return false;
}
memory->rows[memory->size++] = *order;
return true;
}
size_t memoryCount(Orders *self) {
return ((MemoryOrders *)self)->size;
}
void consoleSay(Report *, const char *text) {
printf("%s\n", text);
}
void silentSay(Report *, const char *) {}
//composition root: the only place that sees every layer
//at once, and the only place where an adapter is built.
//C has no unique_ptr: the root holds the adapters by
//value, so they live exactly as long as the root does
typedef struct {
Catalog catalog;
MemoryOrders orders;
Report report;
PlaceOrder useCase;
} ShopApp;
//the use case points into the root, so a root is built
//in its place and never copied afterwards
void shopAppBuild(ShopApp *app, Report report) {
app->catalog = (Catalog){memoryPrice};
app->orders = (MemoryOrders){
.base = {memorySave, memoryCount}};
app->report = report;
app->useCase = (PlaceOrder){&app->catalog,
&app->orders.base,
&app->report, 1001};
}
void shopAppLoud(ShopApp *app) {
shopAppBuild(app, (Report){consoleSay});
}
void shopAppQuiet(ShopApp *app) {
shopAppBuild(app, (Report){silentSay});
}
//client code
ShopApp app;
shopAppLoud(&app);
Item wanted[] = {{"pen", 2}, {"lamp", 1}};
placeOrder(&app.useCase, wanted, 2);
placeOrder(&app.useCase, (Item[]){{"chair", 1}}, 1);
//a second root builds the same use case differently
ShopApp night;
shopAppQuiet(&night);
placeOrder(&night.useCase, (Item[]){{"lamp", 1}}, 1);
Orders *orders = &night.orders.base;
printf("saved %zu\n", orders->count(orders));
//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 moreThe 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. |