Part 2 of 6 · 2 min read
What DI is
A class receives its helpers.
Think of a chef in a restaurant kitchen. The chef does not grow vegetables, mill flour and raise chickens before cooking. Suppliers deliver the ingredients, and the chef cooks.
EJ makes the case with a spell checker that needs a dictionary. Written as a static utility, or as a singleton holding one fixed dictionary, the checker bets that a single dictionary will serve for all time. That bet fails. Every language needs its own word list, special fields need special lists, and a test may want a tiny one. EJ concludes that a class whose behaviour depends on some underlying resource should not be a static utility or a singleton. The remedy is plain: give the constructor the resource when building each instance. This is one kind of dependency injection. The dictionary is what the checker depends on, and it arrives from outside at creation time.
CC states the same idea more broadly. An object should not be in charge of building the things it depends on. It should leave that work to some other authority, most often the program's main routine or a dedicated container. This is "inversion of control" applied to object creation. It also supports the single responsibility principle, because the class stops having two jobs: its own work, and making its helpers.
EJ remarks that the technique is so plain that many programmers use it for years before learning its name. It handles any number of dependencies, keeps classes immutable, and lets many clients share the same helpers.
Dependency injection
Dependency injection means that a class receives the objects it depends on from the outside, instead of creating them or looking them up itself.
Example: new BookingService(clock, notifier, store).
Dependency
A dependency is an object that a class needs in order to do its work.
Example: the Notifier that a BookingService calls.
Check yourself: 1. Why does EJ reject a singleton dictionary in the spell checker? 2. What responsibility does a class give up when it uses DI? 3. Which two parts of the code does CC say usually build the objects?