遇见橄榄树下的雷诺阿:步步为营 .NET 代码重构学习笔记 六、移动函数和移动值域(Move Method And Move Field)
来源:百度文库 编辑:九乡新闻网 时间:2024/04/29 10:41:14
步步为营 .NET 代码重构学习笔记 六、移动函数和移动值域(Move Method And Move Field)
2011-05-23 21:55byspring yang,991visits,网摘,收藏,编辑Move Method
概述
程序中,有个函数与其所驻class之外的另一个class进行更多交流,调用后者或被后者调用
动机(Motivation)
如果一个class有太多行为,或如果一个class与另一个class有太多合作而形成高度耦合(highly coupled),我们就会搬移函数。通过这种手段,我们可以使系统中的classes更简单,这些classes最终也将更干净利落地实现系统交付的任务。
示例
01
public
class
MoveMethod
02
{
03
private
AccountType _type;
04
private
int
_daysOverdrawn;
05
public
double
OverDraftCharge()
06
{
07
if
(_type.IsPremium())
08
{
09
double
result = 10;
10
if
(_daysOverdrawn > 7)
11
result += (_daysOverdrawn - 7) * 0.85;
12
return
result;
13
}
14
else
15
return
_daysOverdrawn * 1.75;
16
}
17
public
double
BankCharge()
18
{
19
double
result = 4.5;
20
if
(_daysOverdrawn > 0)
21
result += OverDraftCharge();
22
return
result;
23
}
24
}
25
26
public
class
AccountType
27
{
28
public
bool
IsPremium()
29
{
30
return
true
;
31
}
32
}
改为
01
public
class
MoveMethod
02
{
03
private
AccountType _type;
04
05
public
double
BankCharge()
06
{
07
double
result = 4.5;
08
if
(_type._daysOverdrawn > 0)
09
result += _type.OverDraftCharge();
10
return
result;
11
}
12
}
13
14
public
class
AccountType
15
{
16
private
int
_daysOverdrawn;
17
18
public
int
DaysOverdrawn
19
{
20
get
{
return
_daysOverdrawn; }
21
set
{ _daysOverdrawn = value; }
22
}
23
24
public
bool
IsPremium()
25
{
26
return
true
;
27
}
28
29
public
double
OverDraftCharge()
30
{
31
if
(IsPremium())
32
{
33
double
result = 10;
34
if
(_daysOverdrawn > 7)
35
result += (_daysOverdrawn - 7) * 0.85;
36
return
result;
37
}
38
else
39
return
_daysOverdrawn * 1.75;
40
}
41
}
Move Field(搬移值域)
概述
在target class建立一个new field,修改source field的所有用户,令它们改用new field。
动机(Motivation)
对于一个field(值域),在其所驻class之外的另一个class中有更多函数使用了它,我就会考虑搬移这个field。
示例
01
public
class
MoveMethod
02
{
03
private
AccountType _type;
04
private
double
_interestRate;
05
public
double
InterestForAmountDay(
double
amount,
int
days)
06
{
07
return
_interestRate * amount * days / 365;
08
}
09
}
10
11
public
class
AccountType
12
{
13
14
}
改为
01
public
class
MoveMethod
02
{
03
private
AccountType _type;
04
05
public
double
InterestForAmountDay(
double
amount,
int
days)
06
{
07
return
_type.InterestRate * amount * days / 365;
08
}
09
}
10
11
public
class
AccountType
12
{
13
private
double
_interestRate;
14
public
double
InterestRate
15
{
16
get
{
return
_interestRate; }
17
set
{ _interestRate = value; }
18
}
19
}
总结
把公用函数和值域放到其基类中去,方便其它函数调用。
步步为营 .NET 代码重构学习笔记 六、移动函数和移动值域(Move Method And Move Field)
步步为营 .NET 代码重构学习笔记 三、内联方法(Inline Method)
步步为营 .NET 代码重构学习笔记 九
步步为营 .NET 代码重构学习笔记 十一
步步为营 .NET 代码重构学习笔记 十二
步步为营 .NET 代码重构学习笔记 一、为何要代码重构
步步为营 .NET 代码重构学习笔记 四、临时变量(Temporary Variable)
学习移动字代码
学习笔记——FLASH添加移动字的代码——引自温柔女侠日志
C#.net学习笔记之托管代码&非托管代码
学习笔记——向上移动的日志
学习在“图书馆首页顶部添加移动文字”笔记
图片移动代码11
图片各种移动代码
向上移动的代码
图片移动代码集锦
移动文字代码
图片移动方向代码
移动文字特效代码大全
文字各种移动代码
移动代码用法
移动代码用法
移动字代码
燕飞墨行图片移动代码