I am reading \"Effective Java\" by Joshua Bloch, item 39 make defensive copy, and I have some questions. I always use the following construct:
MyObject.getSo
Defensive copy is a good idea, but you need to understand when and where it gets used. If the web of objects you are manipulating is internal, and it not intended to be thread safe, then the defensive copying is being mis-applied.
On the other hand, if this is web of objects that are getting exposed publicly, then you are at risk of violating Law of Demeter. If so, consider exposing a manipulator API on your myObject
.
As a sidenote, your code sample made the getSomeRef
look like a static API. I would suggest that you name any static API that returns a copy of some singleton accordingly (e.g. copyOfSomething()
). Similarly for a static factory method.