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.
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);
SpellChecker DE = new SpellChecker(de);
System.out.println(EN.isValid("mother"));
System.out.println(DE.isValid("vater"));
}
}
class SpellChecker {
private final String[] dictionary;
public SpellChecker(String[] d) {
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.
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"));
System.out.println(DE.isValid("vater"));
}
}
class SpellCk {
private static String[] dictionary;
public Boolean isValid(String word) {
return Arrays.asList(dictionary).contains(word);
}
public void setDictionary(String[] d) {
dictionary = d;
}
}