如今就重構來講是很是普通的,雖然咱們常常會漏掉或忽略一些須要重構的地方。方法搬移,正如所定義的那樣,把方法搬移到更適合他的位置。讓咱們看看下面這一段重構前的代碼:spa
理解:方法搬移,正如所定義的那樣,把方法搬移到更適合他的位置。rest
詳解:若是一個類中某個方法,常常被其餘類使用(比自身使用的次數還多),或者這個方法自己不適合這個類,能夠考慮把這個方法搬移到更適合他的類中。code
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; } } }
重構後的代碼:blog
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 } 16 public class AccountInterest 17 { 18 public BankAccount Account { get; private set; } 19 20 public AccountInterest(BankAccount account) 21 { 22 Account = account; 23 } 24 25 public double InterestRate 26 { 27 get { return CalculateInterestRate(); } 28 } 29 30 public bool IntroductoryRate 31 { 32 get { return CalculateInterestRate() < 0.05; } 33 } 34 35 public double CalculateInterestRate() 36 { 37 if (Account.CreditScore > 800) 38 return 0.02; 39 40 if (Account.AccountAge > 10) 41 return 0.03; 42 43 return 0.05; 44 } 45 }
咱們將CalculateInterestRate方法從BankAccount類搬移到 AccountInterest類中,由於這個方法在AccountInterest類中使用,而在自身沒有看到使用。而且CalculateInterestRate方法更適合AccountInterest類。get
搬移後你們能夠看到BankAccount類的職責也單一,同時CalculateInterestRate也放到了常用且適合它的類中了,因此此重構是一個比較好的重構,能讓整個代碼變得更加合理。it