重构同样非常简单,以至于人们并不认为这是一个有价值的重构。迁移方法(Move Method),顾名思义就是将方法迁移到合适的位置。在开始重构前,我们先看看一下代码:

public class BankAccount {
public BankAccount(int accountAge, int creditScore, AccountInterest accountInterest) {
AccountAge = accountAge;
CreditScore = creditScore;
AccountInterest = accountInterest;
}
public int AccountAge{get;private set ;}

public int CreditScore{get;private set ;}

public AccountInterest AccountInterest {get;private set ; }

public double CalculateInterestRate() {
if (CreditScore > 800) return 0.02;
if (AccountAge > 10) return 0.03;
return 0.05;
}
}

public class AccountInterest {
public BankAccount Account{get;private set ;}
public AccountInterest(BankAccount account) {
Account = account;
}
public double InterestRate{
get {
return Account.CalculateInterestRate();
}
}
public bool IntroductoryRate{
get {
return Account.CalculateInterestRate() < 0.05;
}
}
}
这里值得注意的是BankAccount.CalculateInterest方法。当一个方法被其他类使用比在它所在类中的使用还要频繁时,我们就需要使用迁移方法重构了——将方法迁移到更频繁地使用它的类中。由于依赖关系,该重构并不能应用于所有实例,但人们还是经常低估它的价值。 最终的代码应该是这样的:
public class BankAccount {
public BankAccount(int accountAge, int creditScore, AccountInterest accountInterest) {
AccountAge = accountAge;
CreditScore = creditScore;
AccountInterest = accountInterest;
}
public int AccountAge { get; private set; }
public int CreditScore { get; private set; }
public AccountInterest AccountInterest {get;private set;}
}

public class AccountInterest {
public BankAccount Accountm{ get; private set ; }
public AccountInterest(BankAccount account) {
Account = account;
}

public double InterestRate {
get {
return CalculateInterestRate();
}
}
public bool IntroductoryRate {
get {
return CalculateInterestRate() < 0.05;
}
}

public double CalculateInterestRate() {
if (Account.CreditScore > 800) return 0.02;
if (Account.AccountAge > 10) return 0.03;
return 0.05;
}
}
简单吧。。
 
 





posted on 2016-08-18 16:56  jgig11  阅读(356)  评论(0编辑  收藏  举报