Refactoring: Encapsulate Collection
今天看NFS-RPC的源码,看到有这样的代码:Collections.unmodifiableList(servers);突然想起来自己之前看重构时的一种叫Encapsulate Collection的思想,今天以代码为主线再来回顾下: public class Company { private String companyName;//the name of company private List<String> clerkList;//the clerk list //companyName,clearList getter and setter method ........ } 我们封装了一个公司类,公司类中包含一个公司名和公司员工的属性,其中公司员工使用List存放。看似完美,然后我们在其他地方使用Company这个类: Company company = new Company(); List<String> list = company.getClerkList(); list.add("guolei"); 有没有发现什么怪异的地方?在我们获得list的引用后,可以直接操作list,而无需通过company对象。在面向对象的角度来看,这是不正确的设计思想。同样这样的代码看起来也不优雅。这个时候我们引出Collections.unmodifiableList()方法