REMEMBER JAVA

MINTE9
2REMEMBER




Last update:   26-07-2021

DEPENDENCY INJECTION

p20 ! Dependency Injection uses resource provided by client in constructor. The class does not create the resource directly.
 RunCode
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;

class App {

    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("muther")); // false
    }
}

class SpellChecker {

    private final String[] dictionary;

    public SpellChecker(String[] d) { // Look Here

        dictionary = Objects.requireNonNull(d);
    }

    public Boolean isValid(String word) {
        return Arrays.asList(dictionary).contains(word);
    }
}
... 22 lines
˄˄˄
p20 Using a static utility is inflexible and untestable. This approach assumes that there is only one dictionary at a time.
 RunCode
import java.util.Arrays;

class App {

    public static void main(String[] args) {

        SpellChecker EN = new SpellChecker();
        EN.setDictionary(new String[] {"mother", "father"});

        SpellChecker DE = new SpellChecker();
        DE.setDictionary(new String[] {"mutter", "vater"});

        System.out.println(EN.isValid("mother")); // false - Error !
        System.out.println(DE.isValid("mutter")); // true
    }
}

class SpellChecker {

    private static String[] dictionary; // Look Here

    public Boolean isValid(String word) {
        return Arrays.asList(dictionary).contains(word);
    }

    public void setDictionary(String[] d) {
        dictionary = d;
    }
}
... 20 lines
˄˄˄

Questions    
No. 57   Composition
CARD
56

        A B C D E F
🔔
1/2