【Java重構系列】重構31式之搬移方法

來源:互聯網
上載者:User

與搬移方法相似的還有一種重構手段是搬移欄位(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;}}

重構心得:

,指的是一個方法對某個類的興趣高過對自己所處類的興趣,例如某個方法需要訪問另一個類中大量的資料成員,此時,也非常適合使用搬移方法重構。讓方法能夠前往它的夢想王國不是件很有意義的事情嗎?如果一個方法用到了多個類的功能,那麼這個方法放在哪個類中更合適呢?常用的做法是判斷哪個類擁有最多被此方法使用的資料,然後將這個方法和那些資料放在一起。在這種情況下,搬移方法的時機不是判斷它被哪個類調用更多,而是判斷它更需要哪個類提供的資料,這跟上面的重構執行個體有些區別。

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.