Move Method
概述
程序中,有个函数与其所驻class之外的另一个class进行更多交流,调用后者或被后者调用
动机(Motivation)
如果一个class有太多行为,或如果一个class与另一个class有太多合作而形成高度耦合(highly coupled),我们就会搬移函数。通过这种手段,我们可以使系统中的classes更简单,这些classes最终也将更干净利落地实现系统交付的任务。
示例
01 |
public class MoveMethod |
03 |
private AccountType _type; |
04 |
private int _daysOverdrawn; |
05 |
public double OverDraftCharge() |
07 |
if (_type.IsPremium()) |
10 |
if (_daysOverdrawn > 7) |
11 |
result += (_daysOverdrawn - 7) * 0.85; |
15 |
return _daysOverdrawn * 1.75; |
17 |
public double BankCharge() |
20 |
if (_daysOverdrawn > 0) |
21 |
result += OverDraftCharge(); |
26 |
public class AccountType |
28 |
public bool IsPremium() |
改为
01 |
public class MoveMethod |
03 |
private AccountType _type; |
05 |
public double BankCharge() |
08 |
if (_type._daysOverdrawn > 0) |
09 |
result += _type.OverDraftCharge(); |
14 |
public class AccountType |
16 |
private int _daysOverdrawn; |
18 |
public int DaysOverdrawn |
20 |
get { return _daysOverdrawn; } |
21 |
set { _daysOverdrawn = value; } |
24 |
public bool IsPremium() |
29 |
public double OverDraftCharge() |
34 |
if (_daysOverdrawn > 7) |
35 |
result += (_daysOverdrawn - 7) * 0.85; |
39 |
return _daysOverdrawn * 1.75; |
Move Field(搬移值域)
概述
在target class建立一个new field,修改source field的所有用户,令它们改用new field。
动机(Motivation)
对于一个field(值域),在其所驻class之外的另一个class中有更多函数使用了它,我就会考虑搬移这个field。
示例
01 |
public class MoveMethod |
03 |
private AccountType _type; |
04 |
private double _interestRate; |
05 |
public double InterestForAmountDay( double amount, int days) |
07 |
return _interestRate * amount * days / 365; |
11 |
public class AccountType |
改为
01 |
public class MoveMethod |
03 |
private AccountType _type; |
05 |
public double InterestForAmountDay( double amount, int days) |
07 |
return _type.InterestRate * amount * days / 365; |
11 |
public class AccountType |
13 |
private double _interestRate; |
14 |
public double InterestRate |
16 |
get { return _interestRate; } |
17 |
set { _interestRate = value; } |
总结
把公用函数和值域放到其基类中去,方便其它函数调用。