Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 536
jasonline Avatar asked Aug 12 '11 03:08

jasonline


People also ask

Should getters and setters be in class diagram?

You should not include getters and setters in your diagram until they do something special: null checking and so on. But it is a sign of bad design, so general answer is "No, you should not".

What is getters and setters in classes?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

How do you use setters and getters in two different classes?

To fix this, you need to pass a reference to the GetterAndSetter instance from class A to B . You can do this e.g. by passing it as a parameter to a method of B , or by creating a new instance of A in B and calling a method that provides an instance of GetterAndSetter .

Where do you put getters and setters?

The Java coding convention states that methods (getters and setters are methods) should be after constructors declarations. It just a convention and it exists to make code easier to read in general.


1 Answers

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.

like image 69
TofuBeer Avatar answered Sep 22 '22 17:09

TofuBeer