Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to return an ImmutableMap or a Map?

Let's say I'm writing a method that should return a Map. For instance:

public Map<String, Integer> foo() {   return new HashMap<String, Integer>(); } 

After thinking about it for a while, I've decided that there is no reason to modify this Map once it is created. Thus, I would like to return an ImmutableMap.

public Map<String, Integer> foo() {   return ImmutableMap.of(); } 

Should I leave the return type as a generic Map, or should I specify that I'm returning an ImmutableMap ?

From one side, this is exactly why interfaces were created for; to hide the implementation details.
On the other hand, if I'll leave it like this, other developers might miss the fact that this object is immutable. Thus, I won't achieve a major goal of immutable objects; to make the code more clear by minimizing the number of objects that can change. Even worst, after a while, someone might try to change this object, and this will result in a runtime error (The compiler will not warn about it).

like image 727
AMT Avatar asked Jun 28 '16 23:06

AMT


People also ask

What is ImmutableMap?

ImmutableMap, as suggested by the name, is a type of Map which is immutable. It means that the content of the map are fixed or constant after declaration, that is, they are read-only. If any attempt made to add, delete and update elements in the Map, UnsupportedOperationException is thrown.

Why are maps immutable?

An Immutable Map, on the other hand, contains its own private data and doesn't allow modifications to it. Therefore, the data cannot change in any way once an instance of the Immutable Map is created.

Is map mutable in Java?

Mutable maps supports modification operations such as add, remove, and clear on it. Unmodifiable Maps are “read-only” wrappers over other maps. They do not support add, remove, and clear operations, but we can modify their underlying map.


1 Answers

  • If you are writing a public-facing API and that immutability is an important aspect of your design, I would definitely make it explicit either by having the name of the method clearly denotes that the returned map will be immutable or by returning the concrete type of the map. Mentioning it in the javadoc is not enough in my opinion.

    Since you're apparently using the Guava implementation, I looked at the doc and it's an abstract class so it does give you a bit of flexibility on the actual, concrete type.

  • If you are writing an internal tool/library, it becomes much more acceptable to just return a plain Map. People will know about the internals of the code they are calling or at least will have easy access to it.

My conclusion would be that explicit is good, don't leave things to chance.

like image 187
Dici Avatar answered Oct 16 '22 04:10

Dici