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:
public List<Foo> getFoos() {
return Collections.unmodifiableList(this.foos);
}
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:
public void addFoo(Foo foo) {
this.foos.add(foo);
someListener.fooAsBeenAdded(foo);
}
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.
Documentation is the way you (should) know. MyObject
should document whether the things it exposes can or should be used to modify MyObject
itself. You should only ever modify an object in the ways explicitly granted by the class.
For example, here are the Javadocs for two methods in List
, one whose result can't be used to change the List
, and one whose result can change the List
:
toArray()
:
The returned array will be "safe" in that no references to it are maintained by this list. (In other words, this method must allocate a new array even if this list is backed by an array). The caller is thus free to modify the returned array.
subList()
:
The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.
I would say that silence from the documentation means that you shouldn't use it to mutate the object (use it only for read-only purposes).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With