Wiring the App Together

The library's checkout service builds its own storage and reads the real clock, so it can't be tested or changed. Hand it what it needs instead.

Updated

Plan It, Build It

  1. Meet the Library API: Plan It, Build It (Journeyman): The fourth pass starts with a community library's checkout service, planned as a class diagram and built as version 1 in five languages, and then asked the question every pass starts with: what's likely to change? The answer shows why a class that builds its own storage and reads the real clock will hurt.

Hand Me What I Need

  1. Dependency Injection: Hand Me What I Need (Journeyman): When a class builds its own database and reads the real clock, nothing outside it can change either one, so its rules can't be tested; dependency injection has the class ask for them in its constructor, and whoever makes it hands them in, which finishes the idea Pass 1 started with the bakery's settings.
  2. Containers: Who Does the Handing Out (Journeyman): Once every class asks for what it needs, someone has to make the parts and hand them out; doing it in one place at the start of the app (the composition root) keeps it from being copied everywhere, and a container automates that place, with lifetimes that say whether a part is made once for the app, once per request, or new every time.

Ask for the Book, Not the Shelf

  1. Repository: Ask for the Book, Not the Shelf (Journeyman): When the checkout service talks to the database in the database's own words (tables, rows, columns, dates stored as text), every class that needs loans copies that code, tests need a database, and a new database means editing them all; a repository puts loans behind one interface in the app's own words, so a class asks for a loan and never learns where it's kept.
  2. Testing with Fakes: Why This Pays Off (Journeyman): Because the checkout service is handed its clock and its loan repository, a test can hand it a clock set to any day and loans kept in memory, so every late-fee rule and the five-book limit are checked in a few milliseconds, with no database and no waiting; this lesson writes those tests, names the kinds of stand-in (fakes, stubs and mocks), and says what they can't catch.

Exercise: The Library Checkout

  1. Exercise: The Library Checkout (Journeyman): Take a ticket from Riverside Community Library: the board wants every late-fee rule tested, and the test team's tests hand the checkout service a clock they can set and loans kept in memory. Change the working service so it uses what it's handed, opens no database in tests, and still runs the real library, with the tests green throughout.