简体   繁体   中英

Static map in class - public or private?

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));
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM