與搬移方法相似的還有一種重構手段是搬移欄位(Move Field),即搬移屬性。
.),可見該重構的重要性。
package sunny.refactoring.two.before;class BankAccount {private int accountAge;private int creditScore;private AccountInterest accountInterest;public BankAccount(int accountAge, int creditScore, AccountInterest accountInterest) {this.accountAge = accountAge;this.creditScore = creditScore;this.accountInterest = accountInterest;}public int getAccountAge() {return this.accountAge;}public int getCreditScore() {return this.creditScore;}public AccountInterest getAccountInterest() {return this.accountInterest;}public double calculateInterestRate() {if (this.creditScore > 800) {return 0.02;}if (this.accountAge > 10) {return 0.03;}return 0.05;}}class AccountInterest {private BankAccount account;public AccountInterest(BankAccount account) {this.account = account;}public BankAccount getAccount() {return this.account;}public double getInterestRate() {return account.calculateInterestRate();}public boolean isIntroductoryRate() {return (account.calculateInterestRate() < 0.05);}}
package sunny.refactoring.two.after;class BankAccount {private int accountAge;private int creditScore;private AccountInterest accountInterest;public BankAccount(int accountAge, int creditScore, AccountInterest accountInterest) {this.accountAge = accountAge;this.creditScore = creditScore;this.accountInterest = accountInterest;}public int getAccountAge() {return this.accountAge;}public int getCreditScore() {return this.creditScore;}public AccountInterest getAccountInterest() {return this.accountInterest;}}class AccountInterest {private BankAccount account;public AccountInterest(BankAccount account) {this.account = account;}public BankAccount getAccount() {return this.account;}public double getInterestRate() {return calculateInterestRate();}public boolean isIntroductoryRate() {return (calculateInterestRate() < 0.05);}//將calculateInterestRate()方法從BankAccount類搬移到AccountInterest類 public double calculateInterestRate() {if (account.getCreditScore() > 800) {return 0.02;}if (account.getAccountAge() > 10) {return 0.03;}return 0.05;}}
重構心得:
,指的是一個方法對某個類的興趣高過對自己所處類的興趣,例如某個方法需要訪問另一個類中大量的資料成員,此時,也非常適合使用搬移方法重構。讓方法能夠前往它的夢想王國不是件很有意義的事情嗎?如果一個方法用到了多個類的功能,那麼這個方法放在哪個類中更合適呢?常用的做法是判斷哪個類擁有最多被此方法使用的資料,然後將這個方法和那些資料放在一起。在這種情況下,搬移方法的時機不是判斷它被哪個類調用更多,而是判斷它更需要哪個類提供的資料,這跟上面的重構執行個體有些區別。