Dependency injection
Giving an object its dependencies instead of letting it create them: constructor and setter injection, the role of the assembler or container, and the effect on tests.
- 30 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Dependency: what is it?
Show the answer
An object a class needs in order to do its work: a sending service, a data store, a clock.
The problem is not having dependencies, it is creating them yourself with
new: the class ends up tied to one specific implementation.Which version of
Commandeapplies constructor injection?Commande(Notifieur n) { this.n = n; }Commande() { this.n = new ServiceMail(); }void setNotifieur(Notifieur n) { this.n = n; }Commande() { this.n = Notifieurs.parDefaut(); }, a static factory
Show the answer
Commande(Notifieur n) { this.n = n; }The first receives its dependency at creation. The second is setter injection. The other two create or look up their dependency themselves: the class stays tied to an implementation.
A class that creates its concrete dependency itself with … is tied to that implementation and can no longer be tested with a fake.
Show the answer
A class that creates its concrete dependency itself with new is tied to that implementation and can no longer be tested with a fake.
The
newkeyword in business code is the signal to look for: creation belongs to the assembler, not the class that uses the object.Dependency injection: what is it?
Show the answer
The technique of supplying an object, from outside, with the objects it needs, instead of letting it build them itself.
The class only knows the interface of what it uses; the implementation can change, for a test for instance, without touching it.
Commandecreates its service itself withnew ServiceMail(). The tests send real mail on every run. Which fix?- Make
ServiceMaila singleton and call it throughServiceMail.instance() - Define a
Notifieurinterface, whichCommandereceives through its constructor - Move the
new ServiceMail()into a private method ofCommande - Switch off sending in
ServiceMailwhen an environment variable asks for it
Show the answer
Define a
Notifieurinterface, whichCommandereceives through its constructorA singleton or a private method keep
Commandetied toServiceMail. The environment flag puts test code in production code. Only injection allows passing a double that sends nothing.- Make