Dependency Injection
What is Dependency Injection, and why is it beneficial? What are the drawbacks of using static dependencies? How does Dependency Injection facilitate unit testing?
Resource
Dependency Injection decouples components by providing the necessary dependencies from external sources. It is easier to replace or update those dependencies without affecting the component's code.
/**
* With Dependency Injection ...
* the class does not create the resource directly.
*/
package com.minte9.effective.dependency_injection;
import java.util.Arrays;
import java.util.Objects;
public class ResourceApp {
public static void main(String[] args) {
String[] en = new String[] {"mother", "father"};
String[] de = new String[] {"mutter", "vater"};
SpellChecker EN = new SpellChecker(en); // Look Here
SpellChecker DE = new SpellChecker(de);
System.out.println(EN.isValid("mother")); // true
System.out.println(DE.isValid("vater")); // false
}
}
class SpellChecker {
private final String[] dictionary;
public SpellChecker(String[] d) { // Look Here - DI
dictionary = Objects.requireNonNull(d);
}
public Boolean isValid(String word) {
return Arrays.asList(dictionary).contains(word);
}
}
Static
Static dependencies are tightly coupled to the component. Changing the dependency or using a different implementation is difficult since the component relies on a specific instance or state of the dependency.
/**
* Using a static resource insteed of Dependency Injection.
*
* This approach makes the false assumtion ...
* that there is only one dictionary at a time.
*/
package com.minte9.effective.dependency_injection;
import java.util.Arrays;
public class StaticApp {
public static void main(String[] args) {
SpellCk EN = new SpellCk();
EN.setDictionary(new String[] {"mother", "father"});
SpellCk DE = new SpellCk();
DE.setDictionary(new String[] {"mutter", "vater"});
System.out.println(EN.isValid("mother")); // false - Error !
System.out.println(DE.isValid("vater")); // true
}
}
class SpellCk {
private static String[] dictionary; // Look Here
public Boolean isValid(String word) {
return Arrays.asList(dictionary).contains(word);
}
public void setDictionary(String[] d) {
dictionary = d;
}
}
Last update: 444 days ago