12、 尽量减少对参数的隐含传递。
两个方法处理类内部同一个数据(域),并不意味着它们就是对该数据(域)做处理。许多时候,该数据(域)应该作为方法的参输入数,而不是直接存取,在工具类的设计中尤其应该注意。例如:
public class Test{
private List pool = new Vector();
public void testAdd(String str){
pool.add(str);
}
public Object testGet(int index){
pool.get(index);
}
}
两个方法都对List对象pool做了操作,但是,实际上,我们可能只是想对List接口的不同实现Vector、ArrayList等做存取测试。所以,代码应该这样写:
public class Test{
private List pool = new Vector();
public void testAdd(List pool, String str){
pool.add(str);
}
public Object testGet(List pool, int index){
pool.get(index);
}
}
参考资料
设计模式
apache 小组的jakarta 项目的Avalon子项目(http://jakarta.apache.org/),是关于代码复用的,Commons子项目(http://jakarta.apache.org/commons/index.html)也有部分内容。
Thinking in Java