JAVA

  minte9
REMEMBERS




Last update:   01-11-2021

Resource

p20 Dependency Injection uses resource provided by client in constructor.
 
/**
 * 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

Using a static utility is inflexible and untestable.
 
/**
 * 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;
    }
}

Questions     github Effective
Composition
        A B C D E F
🔔
1/2