Recently, I have a heated discussion on this issue.
Suppose I created this method in Java:
public Set<String> getRich() { return ImmutableSet<String> ....; }
Whenever I see this in a stretch request, I scream and try to explain why this is wrong. By doing this, I misled the consumers of my method on the promise of a kit. This means that they can remove or add items. javac will be happy to compile, but there will be a RuntimeException . Add to this that he violates the Liskov Principle of Replacement .
Personally, I always do:
public ImmutableSet<String> getRich() { return ImmutableSet<String> ....; }
Thus, no one is going to shoot himself in the leg.
One suggested approach is Iterable Return . I think this is bad, because the consumer of this method will lose the potential power of HashSet, HashMap or something else (cannot call set.get (hash)).
Another approach - as a consumer - is to create a copy of the output of the getRich () method. But how will you be sure that consumers will do it?
And, of course, you have people who will adhere to the principles of OOP design and say: "Always program interfaces." For me - in this particular case - this is the worst option.
How would you handle this?
(Off topic: this case is a great example of how static typing can provide validity, but will never guarantee legitimacy).
source share