小規模的再造
Refactoring 結構再造
Refactoring 是有規律的技巧重新結構現有的程序碼,改變內部的結構而保留外部的性質.它的核心是一系列小規模的性質保留的轉換.各自的轉換(refactoring) 做一點點,可是一連串的轉換能夠引起重大的結構再造.
一些 Refactoring 實例:
-------------------------------------------
Decompose Conditional 分解條件
-------------------------------------------
你有復雜的條件述句 (if-then-else statement)
=>
從條件抽出方式,然後部分,然後其他部分.
if (date.before (SUMMER_START) || date.after(SUMMER_END)) {
charge = quantity * _winterRate + _winterServiceCharge;
} else {
charge = quantity * _summerRate;
}
=>
if (notSummer(date)) {
charge = winterCharge(quantity);
} else {
charge = summerCharge (quantity);
}
----------------------------------------
Reverse Conditional 反向條件
----------------------------------------
你有條件,如果反向它的意思會比較容易明白
=>
反向條件的意思,重排條件述句次序
if ( !isSummer( date ) )
charge = winterCharge( quantity );
else
charge = summerCharge( quantity );
=>
if ( isSummer( date ) )
charge = summerCharge( quantity );
else
charge = winterCharge( quantity );
----------------------
Split Loop 分化回圈
----------------------
你有做兩件事的回圈
=>
複製回圈
void printValues() {
double averageAge = 0;
double totalSalary = 0;
for (int i = 0; i < people.length; i++) {
averageAge += people[i].age;
totalSalary += people[i].salary;
}
averageAge = averageAge / people.length;
System.out.println(averageAge);
System.out.println(totalSalary);
}
=>
void printValues() {
double totalSalary = 0;
for (int i = 0; i < people.length; i++) {
totalSalary += people[i].salary;
}
double averageAge = 0;
for (int i = 0; i < people.length; i++) {
averageAge += people[i].age;
}
averageAge = averageAge / people.length;
System.out.println(averageAge);
System.out.println(totalSalary);
}
為什麼?
做兩件事的回圈不比分開做的清楚,它也會對進一步的 Refactoring 造成問題.
----------------------------------------------------
更多的 Refactoring
實例
Refactoring home page
註: Refactoring 和 Analysis Patterns 的創作者是同一個人.
0 Comments/評論:
Post a Comment /投評論
<< Home