Effective Java 39 Make defensive copies when needed
2014-04-02 08:44 小郝(Kaibo Hao) 阅读(529) 评论(0) 编辑 收藏 举报Principle
- It is essential to make a defensive copy of each mutable parameter to the constructor.
-
Defensive copies are made before checking the validity of the parameters (Item 38), and the validity check is performed on the copies rather than on the originals.
// Repaired constructor - makes defensive copies of parameters
public Period(Date start, Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
//Make the defensive copies of the parameters before using them.
if (this.start.compareTo(this.end) > 0)
throw new IllegalArgumentException(start +" after "+ end);
}
TOCTOU = time of check/ time of use.
- Do not use the clone method to make a defensive copy of a parameter whose type is subclassable by untrusted parties.
-
Return defensive copies of mutable internal fields.
// Repaired accessors - make defensive copies of internal fields
public Date start() {
return new Date(start.getTime());
}
public Date end() {
return new Date(end.getTime());
}
Summary
If a class has mutable components that it gets from or returns to its clients, the class must defensively copy these components. If the cost of the copy would be prohibitive and the class trusts its clients not to modify the components inappropriately, then the defensive copy may be replaced by documentation outlining the client's responsibility not to modify the affected components.
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。