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.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. 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 Commande applies 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 new keyword 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.

  • Commande creates its service itself with new ServiceMail(). The tests send real mail on every run. Which fix?

    • Make ServiceMail a singleton and call it through ServiceMail.instance()
    • Define a Notifieur interface, which Commande receives through its constructor
    • Move the new ServiceMail() into a private method of Commande
    • Switch off sending in ServiceMail when an environment variable asks for it
    Show the answer

    Define a Notifieur interface, which Commande receives through its constructor

    A singleton or a private method keep Commande tied to ServiceMail. The environment flag puts test code in production code. Only injection allows passing a double that sends nothing.