What's considered best practice when it comes to accessors/mutators and shallow/deep-copy? Or is this question specific to the situation at hand?
i.e.
public class Test {
private final Point point = new Point(-32, 168);
public void getPoint{
return point
}
}
My current 开发者_如何学编程thinking is to use deep-copy for anything mutable; therefore, if Point
provided a setter, I would use deep-copy in Test#getPoint
.
What's the status quo?
[Edit]
After JB Nizet
's answer, I found this great resource.
It depends. Sometimes you want to return a reference to the object, and let the caller modify it. Sometimes you want to return a copy. In the case of a Point, a copy seems more appropriate, though.
Another way to protect the state of your class is to return an unmodifiable view of your field. This can be done by declaring the return type as an interface that only provides read-only methods, or, as in the Java collections api, by returning a wrapper object offering the same interface as the object but throwing exceptions when mutator methods are called.
Whatever the solution you choose, the key is to document what your method does.
精彩评论