duplicate-code
成因:
- 當(dāng)多個(gè)程序員同時(shí)處理同一個(gè)程序的不同部分時(shí)篷朵,通常會(huì)發(fā)生重復(fù)冬殃。
- 還有更微妙的重復(fù)叙谨,當(dāng)代碼的特定部分看起來不同但實(shí)際上執(zhí)行相同的工作時(shí)。 這種重復(fù)可能很難找到和修復(fù)。
- 有時(shí)重復(fù)是有目的的籽腕。 當(dāng)急于趕上最后期限并且現(xiàn)有代碼“幾乎適合”工作時(shí)爱葵,新手程序員可能無法抗拒復(fù)制和粘貼相關(guān)代碼的誘惑施戴。 在某些情況下,程序員根本懶得整理萌丈。
重構(gòu)手法:
- 如果“兩個(gè)沒關(guān)系的類含有相同的代碼”赞哗,使用Extract Class(提煉類),然后分別持有這個(gè)類的引用。
- 如果“同一個(gè)類的兩個(gè)函數(shù)含有相同的代碼”辆雾,使用 Extract Method (提煉函數(shù))并在兩個(gè)地方調(diào)用新函數(shù)肪笋。
- 如果“兩個(gè)互為兄弟的子類內(nèi)含相同的表達(dá)式”,1度迂、先使用 Extract Method (提煉函數(shù))藤乙,然后再對提煉出來的函數(shù)使用Pull Up Method(函數(shù)上移)2、如果重復(fù)的代碼之間只是相似惭墓,則先使用 Extract Method (提煉函數(shù))提取相同的部分坛梁,再使用FormTemplate Method(塑造模板函數(shù)),把相同的部分移到父類里腊凶。
- 有些函數(shù)以不同的算法做相同的事情划咐,則使用Substitute Algorithm(替換算法) 去掉重復(fù)的算法拴念。
目標(biāo):消除重復(fù)的代碼
消除重復(fù)代碼,使程序更精練
附錄:
-
Extract Method(提煉函數(shù))
void printOwing() {
printBanner();
// Print details.
System.out.println("name: " + name);
System.out.println("amount: " + getOutstanding());
}
void printOwing() {
printBanner();
printDetails(getOutstanding());
}
void printDetails(double outstanding) {
System.out.println("name: " + name);
System.out.println("amount: " + outstanding);
}
-
Pull Up Method(函數(shù)上移)
-
FormTemplate Method(塑造模板函數(shù))
-
Extract Class(提煉類)
-
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 "";
}