Extract Method
将一段代码放入一个独立函数中,并让函数名称解释该函数的用途。
动机:当看到一个过长的函数或者一段需要注释才能让人理解用途的代码,一般将这个代码放入一个独立函数中。并且独立函数的命名要很好的解释这个函数的作用。
范例:无局部变量
void printOwing{
Enumeration e=orders.elements();
double outstanding=0.0;
System.out.println("*****************");
System.out.println("**Customer Owes**");
System.out.println("*****************");
//calculate outstanding
while(e.hasMoreElements){
Order order=(Order)e.nextElement();
outstanding +=each.getAmount();
}
System.out.println("name:"+_name);
System.out.println("amount:"+outstanding);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
提炼后:
void printOwing{
Enumeration e=orders.elements();
double outstanding=0.0;
printBanner();
//calculate outstanding
while(e.hasMoreElements){
Order order=(Order)e.nextElement();
outstanding +=each.getAmount();
}
System.out.println("name:"+_name);
System.out.println("amount:"+outstanding);
}
void printBanner(){
System.out.println("*****************");
System.out.println("**Customer Owes**");
System.out.println("*****************");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
范例:有局部变量
提炼后:
void printOwing{
Enumeration e=orders.elements();
double outstanding=0.0;
printBanner();
//calculate outstanding
while(e.hasMoreElements){
Order order=(Order)e.nextElement();
outstanding +=each.getAmount();
}
printDetails(outstanding);
}
void printBanner(){
System.out.println("*****************");
System.out.println("**Customer Owes**");
System.out.println("*****************");
}
void printDetails(double outstanding){
System.out.println("name:"+_name);
System.out.println("amount:"+outstanding);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
范例:对局部变量再赋值
这里我们只讨论临时变量的问题。被赋值的临时变量也分两种情况。较为简单的情况是:这个变量只在被提炼代码段中使用(后面并未使用)。另一种情况是:这个变量在被提炼代码段中使用后,还使用了这个变量,这样就需要有返回值。
void printOwing{
printBanner();
double outstanding=getOutstanding();
printDetails(outstanding);
}
double getOutstanding(){
Enumeration e=_orders.elements();
double outstanding=0.0;
while(e.hasMoreElements){
Order order=(Order)e.nextElement();
outstanding+=order.getAmount();
}
return outstading;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Enumeration 变量e只是在被提炼码中使用到,所以可以将它整个搬到新函数中。Double 变量 outstanding在被提炼码内外都被用到,所以必须让提炼出来的新函数返回它。
Inline Method
一个函数的本体与名称同样清楚易懂。在函数调用点插入函数本体,然后移除该函数。
动机:有时候遇到某些函数,其内部代码和函数名称同样清晰易读。另一种需要使用该方法是:手上有一群组织不甚合理的函数。
int getRating(){
return (moreThanFiveLateDeliveries())?2:1;
}
boolean moreThanFiveLateDeliveries(){
return _numberOfLateDeliveries>5;
}
1
2
3
4
5
6
|
|