You're violating two rules of OO programming:
- do not talk to strangers
- encapsulation
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…