CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 4 of 6 · 2 min read

The composition root

One place builds the graph.

If every class receives its helpers, someone must build them. CC and CA answer in the same way: main builds the objects and hands them to the application. The application expects that everything has been built and wired. CC points out that the dependency arrows all point away from main, so the application knows nothing about main or the building process. This place is often called the composition root.

public static void main(String[] args) {
    BookingStore store = new MemoryStore();
    BookingService svc = new BookingService(new SystemClock(), new ConsoleNotifier(), store);
    svc.book("asha");
    System.out.println(store.count());
}

For a system clock fixed at 1000 (made up), this prints "notify asha: booked at 1000" and then 1. All new calls for real classes are here. Swapping the console notifier for an email notifier means changing one line in main, and no class under it.

Sometimes the application itself must decide when to create objects, for example a new order line for each item. CC's answer is an abstract factory (module 2): the application calls a factory interface and main supplies the implementation. EJ offers a lighter version: pass a Supplier<T>, a factory that can be called many times.

class IdGenerator {
    private final Supplier<String> make;
    IdGenerator(Supplier<String> make) { this.make = make; }
    String next() { return make.get(); }
}

With a counter behind the supplier, two calls to next() give "B1" and "B2". The class controls when ids are made, and the caller controls how.

Composition root

The composition root is the single place in a program, usually main, where all objects are created and connected.

Example: the main method above.

Check yourself: 1. Where do all the new calls for real classes live? 2. How does a class create many objects without naming their class?