0

I just have a small question about optimization. What is the best between:

- Using a static map in a class and interact with it with static methods.

public class Manager {

    public static Map<String, Long> ids = new HashMap<>();

    public static Long getId(String name) {
        return ids.get(name);
    }

}

public class RandomClass {

    public void randomMethod(String name) {
        Manager.getId(name);
    }

}


- Using only one instance of Manager Object that is saved in the only instance of MainClass and interact with the map with this unique instance of Manager Object.

public class Manager {

    public Map<String, Long> ids = new HashMap<>();

    public Manager() {}

    public Long getId(String name) {
        return ids.get(name);
    }

}

public class MainClass {

    private static MainClass instance;
    private Manager manager;

    public void initialize() {
        manager = new Manager();
    }

    public static MainClass getInstance() {
        return instance;
    }

    public Manager getManager() {
        return manager;
    }

}

public class RandomClass {

    public void randomMethod() {
        MainClass.getInstance().getManager().getId(name);
    }

}

Thank you in advance for your answer.

  • 1
    The second one is cleaner because you can properly inject dependencies and can therefore test the code without much effort. – luk2302 Aug 03 '18 at 12:07
  • Yes it's more "beautiful" but is it more expensive for Java ? I mean, is it more optimized or less than using static map ? Thank you for your quick reply. – MrTigreroux Aug 03 '18 at 12:10
  • That is irrelevant. And most certainly the difference is negligible. – luk2302 Aug 03 '18 at 12:12
  • 1
    The simply rule of thumb is: you don't make things static unless you have to. See is as *abnormality*. It is not your first design option, but your last. – GhostCat Aug 03 '18 at 12:16

0 Answers0