Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

design patterns - Defensive copy from Effective Java

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...