Composing Methods(重新組織你的函數(shù))
1.Extract Method(提煉函數(shù))
代碼段可被組織在一起并獨立出來
void printOwing(double previousAmount)
{
Enumeration e = _orders.elements();
double outstanding = previousAmount * 1.2;
// print banner
System.out.println ("* * * * * * * * * * * * * * * * * * * * * * *");
System.out.println ("Customer Owes ");
System.out.println (" * * * * * * * * * * * * * * * * * * * * * * *");
// calculate outstanding
while (e.hasMoreElements())
{
Order each = (Order) e.nextElement();
outstanding += each.getAmount();
}
//print details
System.out.println ("name:" +_name);
System.out.println ("amount" + outstanding)
}
將這段代碼放進(jìn)一個獨立函數(shù)中傅寡,并讓函數(shù)名稱解釋該函數(shù)的用途
void printOwing(double previousAmount)
{
printBanner();
double outstanding = getOutsta nding(previousAmount * 1.2);
printDetads(outstanding);
}
void printBanner0
{
// print banner
.....
}
double getOutstanding(double initialValue)
{
double result = initialValue;
Enumeration e = orders.elements();
while (e.hasMoreElements())
{
Order each = (Order) e.nextElement();
result += each.getAmount();
}
return result;
}
void printDetails (double outstanding)
{
//print details
...
}
2.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 "";
}
將函數(shù)本體替換為另一個算法
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 "";
}
Simplifying Conditional Expressions(簡化條件表達(dá)式)
3. Decompose Conditional(分解條件式)
你有一個復(fù)雜的條件語句,從if耘柱、else段落中分別提煉出獨立函數(shù)
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);
4.Consolidate Conditional Expression(合并條件式)
你有一系列條件判斷,都得到相同結(jié)果,將這些判斷合并為一個條件式矾飞,并將條件式提煉成為獨立函數(shù)枚冗。
double disabilityAmount()
{
if (_seniority < 2) return 0;
if (_monthsDisabled > 12) return 0;
if (_isPartTime) return 0;
// compute the disability amount
...
}
修改成
double disabilityAmount()
{
if (isNotEligableForDisability()) return 0;
// compute the disability amount
...
}
5.Consolidate Duplicate Conditional Fragments(合并重復(fù)的條件片斷)
在條件式的每個分支上有著相同的一段代碼, 將這段重復(fù)代碼搬移到條件式之外。
if (isSpeciaIDeal())
{
total = price * 0.95
send();
}
else
{
total = price* 0.98
send();
}
修改成
if (isSpeciaIDeal())
total = price * 0.95
else
total = price * 0.98
send();
6.Remove Control Flag(移除控制標(biāo)記)
在一系列布爾表達(dá)式種诞仓,某個變量帶有【控制標(biāo)記】的作用,以break和return取代控制標(biāo)記
void checkSecurity(String[] people) {
boolean found = false;
for (int i = 0; i < people.length; i++) {
if (l found) {
if (people[i].equals ("Don")){
sendAlert();
found = true;
}
if (people[i].equals ("John")){
sendAlert();
found = true;
}
}
}
}
變成
void checkSecurity(String[] people) {
for (int i = 0; i < people.length; i++) {
if (people[i].equals ("Don")){
sendAlert();
break;
}
if (people[i].equals ("John")){
sendAlert();
break;
}
}
}
Making Method Calls Simpler(簡化函數(shù)調(diào)用)
7.Separate Query from Modifier(將查詢函數(shù)和修改函數(shù)分離)
某個函數(shù)既返回對象狀態(tài)值枉侧,又修改對象狀態(tài)。 建立兩個不同的函數(shù)狂芋, 其中一個負(fù)責(zé)查詢榨馁,另一個負(fù)責(zé)修改
將
Customer::getTotalOutstandingAndSetReadyForSummaries(...)
{
...
}
分成兩個函數(shù)
Customer::getTotalOutstanding(...)
{
...
}
Customer::SetReadyForSummaries(...)
{
...
}
8.Parameterize Method(令函數(shù)攜帶參數(shù))
若干函數(shù)做了類似的工作,但在函數(shù)本體中卻包含了不同的值帜矾。建立單一函數(shù)翼虫,以參數(shù)表達(dá)那些不同的值
Dollars baseCharge0
{
double result = Math.min(lastUsage(),l00) * 0.03;
if (lastUsage() > 100) {
result += (Math.min (lastUsage(),200) - 100) * 0.05;
};
if (lastUsage() > 200) {
result += (lastUsage() - 200)*0.07;
};
return new Dollars (result);
}
修改成
Dollars baseCharge()
{
double result = usagelnRange(0, 100)* 0.03;
result += usagelnRange (100,200) * 0.05;
result += usagelnRange (200, Integer.MAX VALUE) * 0.07
return new Dollars (result);
}
int usagelnRange(int start, int end)
{
if (lastUsage() > start)
return Math.min(lastUsage(),end) -start
else
return 0;
}
9.Replace Parameter with Explicit Methods(以明確函數(shù)取代參數(shù))
函數(shù)實現(xiàn)完全取決于參數(shù)值而采取不同反應(yīng)屑柔,針對該參數(shù)的每一個可能值,建立一個獨立函數(shù)
void setValue (String name, int value)
{
if (name.equals("height"))
_height = value;
if (name.equals("width"))
_width = value;
Assert.shouldNeverReachHere();
}
改成
void setHeight(int arg)
{
_height = arg;
}
void setWidth (int arg)
{
_width = arg;
}
10.Replace Conditional with Polymorphism(以多態(tài)取代條件式)
你手上有個條件式珍剑,它根據(jù)對象類型的不同而選擇不同的行為掸宛。那么,將整個條件式的每個分支放進(jìn)子類的重載方法中招拙, 然后將原始函數(shù)聲明為抽象方法
double getSpeed()
{
switch (_type) {
case EUROPEAN:
return getBaseSpeed();
case AFRICAN:
return getBaseSpeed() - getLoadFactor() *_numberOfCoconuts;
case NORWEGIAN_BLUE:
return (isNailed) ? 0 : getBaseSpeed(_voltage);
}
throw new RuntimeException ("Should be unreachable");
}
修改成
image.png