jasonline
jasonline

Reputation: 9054

Getters/setters of a class having a map

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?

Upvotes: 12

Views: 15757

Answers (4)

fastcodejava
fastcodejava

Reputation: 41117

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.

Upvotes: 1

oksayt
oksayt

Reputation: 4365

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

Upvotes: 10

TofuBeer
TofuBeer

Reputation: 61536

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.

Upvotes: 4

Rob Goodwin
Rob Goodwin

Reputation: 2777

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

Upvotes: -5

Related Questions