2

I want to use a static Map in other classes. If you could please tell me which practice is better. I can make it private and provide appropriate getters and setters for key and value. On the other hand, the second option is just to declare it public and in those classes use methods from built-in Map Collection.

First option example:

public class MapClass{
    private static Map<int, String> map = new HashMap<>();

    public String getValueForKey(int key){
        return map.get(key);
    }

    // other methods
}

public class DifferentClass{
     public void writeString(int number){
        System.out.println(MapClass.getValueForKey(number));
    }
}

Second option example:

public class MapClass{
    public static Map<int, String> map = new HashMap<>();
}

public class DifferentClass{
    public void writeString(int number){
        System.out.println(MapClass.get(number));
    }
}
K.Rzepecka
  • 322
  • 2
  • 9
  • 3
    It completely depends on your needs. Remember that it is mutable and if you declare it as `public` then new entries can be added. If you want to prevent that behavior then you should keep it `private` and only expose functions like `getKey()` or `getValue()`. – user2004685 Jan 05 '17 at 18:42
  • 1
    Biggest problem if you make it public: `MapClass.map = null;`. But if you make it `final` this slightly alleviates the problem. Also a question of if you want to offer thread-safety in your containing class. Related thread: http://stackoverflow.com/questions/1568091/why-use-getters-and-setters – ebyrob Jan 05 '17 at 18:43
  • It would say, that using private should be better in most cases - of course not always. Reason is simple: there's bettter encapsulation of code. When you wrote your custom methods to access map, then you can change implementation, use other library - even with totally different API - and have much more control. Of course sometimes public may be better, but currently I see no other reason for public than your internal API ;) Long long answer could be posted. You wrote that you are on university, is this a part of your assignment? Maybe if you post more information, we could help you more :) – T. Gawęda Jan 05 '17 at 18:56
  • 1
    You should first try to find a way NOT to have a singleton map at all. There are very few legitimate use cases and in most situations it can be replaced by a better option design. It's also going to [make testing more difficult](http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/). – assylias Jan 05 '17 at 19:38

1 Answers1

0

I would prefer to use the first way. First of all, all fields of classes should be private if it's possible. Second, objects shouldn't be only containers with getters and setters but they should provide other methods to change the data too(for example getValueForKey(int key) as in first example). It's widely described in a lot of books about OOP.

Karol Jurski
  • 180
  • 1
  • 10