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.getSomeRef().setSomething(somevalue);
which is short for:
SomeRef s = MyClass.getSomeRef();
s.setSomething();
MyObject.setSomeRef(s);
It always works, but I guess if my getSomeRef() was returning a copy then my shortcut would not work, how can I know if the implementation of MyObject is hidden if it is safe to use a shortcut or not?
You’re violating two rules of OO programming:
Note that these rules are just rules, and that they can, or even must be broken sometimes.
But if some data is owned by an object, and the object is supposed to guarantee some invariants on the objects it owns, then it should not expose its mutable internal data structures to the outside. Hence the need for a defensive copy.
Another often used idiom is to return unmodifiable views of the mutable data structures:
This idiom, or the defensive copy idiom, can be important, for example, if you must make sure that every modification to the list goes through the object:
If you don’t make a defensive copy or return an unmodifiable view of the list, a caller could add a foo to the list directly, and the listener would not be called.