假设我们有这样一种方法:
public List<Animal> findByKeyword(String keyword){
List<Animal> animals = new ArrayList<Animal>();
// Validate keyword is not null etc..
// hit db for animals with name like keyword and add to list
// hit db for animals with owner name like keyword and add to list
// hit db for animals with nick name like keyword and add to list
// remove duplicates in the list
return animals;
}
假设这个方法在很多地方使用并假设它有点长......现在我想添加一个像这样的简单布尔值:
public List<Animal> findByKeyword(String keyword,boolean excludeDead){
// code here...
}
唯一的区别应该是这样的:
// remove duplicates in the list
// if(excludeDead) removeDeadAnimalsFromTheList
所以我不想复制粘贴整个方法。但我不想将参数添加到现有方法,因为该方法在很多地方使用(默认情况下excludeDead = false ..说这是一个新要求..)
但问题是,我不想做出这样的改变:
// remove duplicates in the list
// if(excludeDead) removeDeadAnimalsFromTheList
因为如果exludeDead为真,我将不必要地加载所有死亡的动物。所以我想做的是修改:
// hit db for animals with name like keyword and add to list BASED ON THE GIVEN BOOLEAN VALUE
扩展此类代码的最佳方法是什么?有没有办法让参数可选?
请不要认为这是一个真实的代码,我只是想让它变得简单。
答案 0 :(得分:4)
使用默认值
从第一个方法调用第二个方法public List<Animal> findByKeyword(String keyword){
return findByKeyword(keyword, false); //your default value
}
public List<Animal> findByKeyword(String keyword,boolean excludeDead){
List<Animal> animals = new ArrayList<Animal>();
// Validate keyword is not null etc..
// hit db for animals with name like keyword and add to list
// hit db for animals with owner name like keyword and add to list
// hit db for animals with nick name like keyword and add to list
// remove duplicates in the list
return animals;
}
答案 1 :(得分:1)
在新实现中调用第一个方法,然后将条件应用于结果列表。
public List<Animal> findByKeyword(String keyword, boolean excludeDead){
List<Animal> list = findByKeyword(keyword);
// Now apply the condition on the list above.
}
答案 2 :(得分:1)
重载方法:
public List<Animal> findByKeyword(String keyword, boolean excludeDead) {
// the original code here
if (excludeDead) {
// additional code in case excludeDead is true
}
}
public List<Animal> findByKeyword(String keyword) {
return findByKeyword(keyword, false);
}
答案 3 :(得分:0)
您应该创建一个新方法
public List<Animal> findByKeyword(String keyword, boolean excludeDead){
List<Animal> animals = new ArrayList<Animal>();
// Validate keyword is not null etc..
// hit db for animals with name like keyword and add to list
// hit db for animals with owner name like keyword and add to list
// hit db for animals with nick name like keyword and add to list
// remove duplicates in the list
// remove duplicates in the list
// if(excludeDead) removeDeadAnimalsFromTheList
return animals;
}
并从现有方法中调用
public List<Animal> findByKeyword(String keyword) {
return findByKeyword(keyword,false);
}
希望这有帮助。