CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 3 of 6 · 2 min read

Injecting dependencies

Clock, store and notifier.

The booking service of Level 3 gets its three outside dependencies through the constructor.

interface Clock    { Instant now(); }
interface Notifier { void send(String to, String msg); }
interface Store    { boolean exists(String id); void save(String id, Instant at); }

class BookingService {
    private final Clock clock; private final Notifier notifier; private final Store store;

    BookingService(Clock c, Notifier n, Store s) { clock = c; notifier = n; store = s; }

    String book(String id, String user, Instant start) {
        if (!start.isAfter(clock.now()))
            throw new IllegalArgumentException("start in the past");
        if (store.exists(id)) return "duplicate";
        store.save(id, start);
        notifier.send(user, "booked " + id);
        return "ok";
    }
}

The service never calls the system clock, never opens a database and never sends a real message. Each of those is behind an interface. In production, main builds the real versions and passes them in (the composition root of Level 3, module 6). In a test, small stand-ins are passed instead.

Java already has a Clock class in java.time, so a real project can use that. The idea is the same.

Three stand-ins cover the example.

class FakeClock implements Clock {
    Instant t;
    FakeClock(Instant t) { this.t = t; }
    public Instant now() { return t; }
    void advance(Duration d) { t = t.plus(d); }
}

class RecordingNotifier implements Notifier {
    final List<String> sent = new ArrayList<>();
    public void send(String to, String m) { sent.add(to + ":" + m); }
}

class MemStore implements Store {
    final Map<String, Instant> m = new HashMap<>();
    public boolean exists(String id) { return m.containsKey(id); }
    public void save(String id, Instant at) { m.put(id, at); }
}

A fake is a simple working version of a dependency, such as an in-memory store. A recording object keeps a list of what it was asked to do, so a test can check it afterward. Hand-written stand-ins like these are short and easy to read. Mocking libraries can build them for you, but a hand-written fake often makes tests clearer and less tied to how the code is written inside.

Check yourself: 1. Which three outside things does BookingService receive? 2. What does RecordingNotifier allow a test to check? 3. Where are the real versions built?