簡述
Substitute Algorithm(替換算法)指你想把一個(gè)算法替換成另一個(gè)更清晰的算法奈搜,將函數(shù)本體替換為另一個(gè)算法帖烘。
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 "";
}
動(dòng)機(jī)
重構(gòu)可以把一些復(fù)雜東西分解為較簡單的小塊,但有時(shí)你就必須壯士斷腕,刪除整個(gè)算法彪见,代之以較簡單的算法儡司。而且解決這類問題往往有好幾種方法娱挨。
做法
- 準(zhǔn)備好另一個(gè)(替換用)算法,讓它通過編譯
- 針對(duì)現(xiàn)有測(cè)試捕犬,執(zhí)行上訴的新算法跷坝。如果結(jié)果與原本結(jié)果相同,重構(gòu)結(jié)束碉碉。
- 如果測(cè)試結(jié)果不同于原先柴钻,在測(cè)試和調(diào)試過程中,以舊算法為比較參照標(biāo)準(zhǔn)垢粮。