2 ms·
> so many of Google’s internal libraries make defensive copies in many places, This, IMO, is a sign of poor design. What are you trying to protect? That the g
by cogman10 1y ago
> so many of Google’s internal libraries make defensive copies in many places,
This, IMO, is a sign of poor design.
What are you trying to protect? That the google library isn't modifying something or that the caller of the google library isn't concurrently modifying something?
Or are your storing off the value for later use?
In any case, it's acceptable in the Javadoc and API to specify "If you give me this, you cannot further modify it". This already happens and is expected in common JDK data-structures. For example, if you put an element into a HashSet and then change the hash, you won't be able to find it again in the HashSet. Nobody complains that's the case because it's a "Well duh, you shouldn't have done that". Similarly, if you mutate a map while accessing it you'll get a "ConcurrentModificationException" or even bad results. Again, completely expected behavior.
If you are worried about your code doing the wrong thing with something, then one defense that is easy to deploy is wrapping that object with one the is unmodifiable. That's why the JDK has the likes of `Collections.unmodifiableSet`. That doesn't do a defensive copy and is just a quick wrapper on the incoming set.
Defensive programming has it's place. However, I think it gets over-deployed.