重构改善既有代码之基础改善方法
在实际开发中有大量的代码块改善方式,这里介绍几种基础的方法。
文章目录
1.Move Method(搬移函数)
你的程序中,有个函数与其所驻类之外的另一个类进行更多交流:调用后者,或被后者调
该函数最常引用的类中建立一个有着类似行为的新函数。将旧函数变成一个单纯的委托函数,或是将旧函数完全移除。
实例:
class Account{
double overdraftCharge() {
if (_type. isPremium()) {
double result = 10;
if (_daysOverdrawn > 7) result += (_daysOverdrawn - 7) * 0.85;
return result;
}
else return_daysOverdrawn * 1. 75;
}
double bankCharge (){
double result = 4.5;
if (_daysOverdrawn > 0) result += overdraftCharge() ;
return result;
}
private AccountType _type ;
private int _daysOverdrawn;
}
在这个例子中,“ 调整”的意思是:
(1)对于使用AccountType特性的语句,去掉 _type;
(2)想办法得到依旧需要的Account类特性。
当我需要使用源类的特性时,有4种选择:
(1)将这个特性也移到目标类;
(2)建立或使用一个从目标类到源类的引用关系;
(3)将源对象当作参数传给目标函数;
(4)如果所需特性是个变量,将它当作参数传给目标函数。
改善:
class AccountType{
double overdraftCharge(Account account) {
if (isPremium()) {
double result = 10;
if (account.getDaysOverdrawn() > 7){
result += (account.getDaysOverdrawn() - 7) * 0.85;
return result ;
}
}else{
return account . getDaysOverdrawn() * 1.75;
}
}
}
class Account{
double bankCharge() {
double result = 4.5;
if (_daysOverdrawn > 0){
result += _type.overdraftCharge(_dayeOverdrawn);
}
return result ;
}
private AccountType _type ;
private int _daysOverdrawn;
}
2.Move Field(搬移字段)
你的程序中,某个字段被其所驻类之外的另一个类更多地用到。
在目标类新建一个字段,修改源字段的所有用户,令它们改用新字段。
实例:
class Account{
private AccountType _type;
private double _interestRate;
double interestForAmount_days(double amount, int days) {
return _interestRate * amount * days / 365;
}
}
我想把表示利率的_interestRate搬移到AccountType类去。目前已有数个函数引用了它,interestForA