Java – getters / setters of classes with maps
•
Java
What are the best practices for implementing / providing getters / setters for courses with maps?
The most common implementations I see are:
public class MyClass { private Map<String,String> myMap; public getMyMap() { /* Return an unmodifiable map */ } public setMyMap(Map<String,String> myMap) { ... } }
Or it is better to provide an interface, such as:
public getMyMap() { /* Return a modifiable map */ } public addToMap(String key,String value) { myMap.put(key,value); }
Why is this method better?
Solution
Both have their uses The methods exposed by the class should have an appropriate level of abstraction For example, if this class is a dog registry supported by map < string, dog >, it can provide the following methods:
void addDog(String name,Dog dog); Dog findByName(String name);
If it is a rule engine that allows the client to specify the entire rule set in one call, it can display the following methods:
void setRules(Map<String,Rule> rules); Map<String,Rule> getRules();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码