31天重构指南之二:移动方法

今天的重构指南是关于移动方法的,移动方法是一个简单却容易被忽略的重构,正如它的名字所表达的意思一样,移动方法就是将方法移动到合适的位置。让我们来看下面的待重构代码:

   1: public class BankAccount
   2: {
   3:     public BankAccount(int accountAge, int creditScore, AccountInterest accountInterest)
   4:     {
   5:         AccountAge = accountAge;
   6:         CreditScore = creditScore;
   7:         AccountInterest = accountInterest;
   8:     }
   9:  
  10:     public int AccountAge { get; private set; }
  11:     public int CreditScore { get; private set; }
  12:     public AccountInterest AccountInterest { get; private set; }
  13:  
  14:     public double CalculateInterestRate()
  15:     {
  16:         if (CreditScore > 800)
  17:             return 0.02;
  18:  
  19:         if (AccountAge > 10)
  20:             return 0.03;
  21:  
  22:         return 0.05;
  23:     }
  24: }
  25:  
  26: public class AccountInterest
  27: {
  28:     public BankAccount Account { get; private set; }
  29:  
  30:     public AccountInterest(BankAccount account)
  31:     {
  32:         Account = account;
  33:     }
  34:  
  35:     public double InterestRate
  36:     {
  37:         get { return Account.CalculateInterestRate(); }
  38:     }
  39:  
  40:     public bool IntroductoryRate
  41:     {
  42:         get { return Account.CalculateInterestRate() < 0.05; }
  43:     }
  44: }
 
上面代码中让我们感兴趣的是BankAccount.CalculateInterest方法,我们需要对它进行重构,重构的提示是我们需要将方法定义在对它使用最多的类中。在这个例子中,我们要将
BankAccount.CalculateInterest方法移动到AccountInterest类中。重构后的代码如下:
   1: public class BankAccount
   2: {
   3:     public BankAccount(int accountAge, int creditScore, AccountInterest accountInterest)
   4:     {
   5:         AccountAge = accountAge;
   6:         CreditScore = creditScore;
   7:         AccountInterest = accountInterest;
   8:     }
   9:  
  10:     public int AccountAge { get; private set; }
  11:     public int CreditScore { get; private set; }
  12:     public AccountInterest AccountInterest { get; private set; }
  13: }
  14:  
  15: public class AccountInterest
  16: {
  17:     public BankAccount Account { get; private set; }
  18:  
  19:     public AccountInterest(BankAccount account)
  20:     {
  21:         Account = account;
  22:     }
  23:  
  24:     public double InterestRate
  25:     {
  26:         get { return CalculateInterestRate(); }
  27:     }
  28:  
  29:     public bool IntroductoryRate
  30:     {
  31:         get { return CalculateInterestRate() < 0.05; }
  32:     }
  33:  
  34:     public double CalculateInterestRate()
  35:     {
  36:         if (Account.CreditScore > 800)
  37:             return 0.02;
  38:  
  39:         if (Account.AccountAge > 10)
  40:             return 0.03;
  41:  
  42:         return 0.05;
  43:     }
  44: }
 

原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/02/refactoring-day-2-move-method.aspx

你可能感兴趣的:(重构)