12

What is the best practice in implementing/providing getters/setters for a class containing a map?

The most common implementation I see is:

public class MyClass { private Map<String, String> myMap; public getMyMap() { /* Return an unmodifiable map */ } public setMyMap(Map<String, String> myMap) { ... } } 

Or would it be better to provide an interface like:

public getMyMap() { /* Return a modifiable map */ } public addToMap(String key, String value) { myMap.put(key, value); } 

And why is such method better?

2
  • I would always try to use the second option where possible, but where you've got to expose javabean getters/setters you sometimes have no choice. Commented Aug 12, 2011 at 3:43
  • 7
    Depends solely on whatever the map represents (thus, the functional requirements). This is usually to be documented on the class and/or the methods. There is no real answer to this. Commented Aug 12, 2011 at 3:43

4 Answers 4

10

Both have their uses. The methods exposed by a class should be of a proper level of abstraction. For example if the class is a registry of dogs backed by a Map<String, Dog>, then it could provide methods like:

void addDog(String name, Dog dog); Dog findByName(String name); 

If it's say a rule engine that allows clients to specify the entire rule set in one call, then it could expose methods like:

void setRules(Map<String, Rule> rules); Map<String, Rule> getRules(); 
Sign up to request clarification or add additional context in comments.

Comments

4

In general I would say try not to return the map at all. Have a method that takes the key and returns the value. Taking a map is ok, as long as you copy it, but a method that takes the key/value and puts it into the map would be my preference.

If you must return the map you should return a read-only version or a copy of it. A set method should also copy the map.

It is a bad idea to allow callers to mutate the data inside of a class without the class knowing, passing or holding onto mutable data is a bad idea.

Comments

1

It totally depends on your requirement. This may suffice in most of the cases. You may not even have a getter method that returns the map. If you use my plug-in, it may help you creating those methods : http://fast-code.sourceforge.net/documentation.htm#create-list-map as eclipse will not help you create the add method.

Comments

-5

I would just provide one. Something like...

public Map<String,String> getMyMap() { return myMap; } 

and when you want to use it then

myClass.getMyMap().put(key,value); 

DISCLAIMER: I did not compile this and test this answer ;)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.