Let's say I'm writing a method that should return a Map . For example:
public Map<String, Integer> foo() { return new HashMap<String, Integer>(); }
After thinking about this for a while, I decided that there was no reason to modify this map after it was created. So, I would like to return ImmutableMap .
public Map<String, Integer> foo() { return ImmutableMap.of(); }
Should I leave the return type as a shared card, or should I indicate that I am returning an ImmutableMap?
On the one hand, this is why interfaces were created; to hide implementation details.
On the other hand, if I leave it like this, other developers may miss the fact that this object is immutable. Thus, I will not achieve the main goal of immutable objects; to make the code more understandable, minimizing the number of objects that can change. Even worse, after some time, someone may try to modify this object, and this will lead to a runtime error (the compiler will not warn about this).
java design-patterns immutable-collections
AMT Jun 28 '16 at 23:30 2016-06-28 23:30
source share