Substitute Algorithm(替换算法)
String foundPerson(String[] people){
for (int i =0; i < people.length; i++){
if (people[i].equals("Don")) {
return "Don";
}
if (people[i].equals("John")) {
return "John";
}
if (people[i].equals("Kent")) {
return "Kent";
}
}
return "";
}
修改后:
String foundPerson(String[] people){
List candidates = Arrays.asList(new String[]{"Don", "John", "Kent"});
for (int i = 0; i < people.length; i++) {
if (candidates.contains(people[i])){
return people[i];
}
}
return "";
}
做法
准备好一个(替换用)算法,让它通过编译
针对现有测试,执行上述的新算法。如果结果与原本结果相同,重构结束。
如果测试结果不同于原先,在测试和调试过程中,以旧算法为比较参照标准。
对于每个测试用例,分别以新旧两种算法执行,并观察两者结果是否相同。这可以帮助你看到哪一个测试用例出现麻烦,以及出现了怎样的麻烦