Chapter 3. Investigating DI

"The best way to predict the future is to invent it."

—Alan Kay

Previously we discussed two methods of connecting objects with their dependencies. In the main we have written classes that accept their dependencies via constructor. We have also occasionally used a single-argument method called a setter method to pass in a dependency. As a recap, here are two such examples from chapter 1:

public class Emailer {
    private SpellChecker spellChecker;

    public Emailer(SpellChecker spellChecker) {
        this.spellChecker = spellChecker;
    }
}

The same class accepting dependencies by setter:

public class Emailer { private SpellChecker spellChecker; public void setSpellChecker(SpellChecker spellChecker) { this.spellChecker = spellChecker; } ...

Get Dependency Injection now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.