Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...