Similar to the moving method, another reconstruction method is to Move the Field, that is, to Move the attribute.
.) To see the importance of this refactoring.
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);} // set calculateInterestRate () the method is moved from the BankAccount class to the AccountInterest class public double calculateInterestRate () {if (account. getCreditScore ()> 800) {return 0.02;} if (account. getAccountAge ()> 10) {return 0.03;} return 0.05 ;}}
Reconstruction experience:
A method is more interested in a class than in its own class. For example, a method needs to access a large number of data members in another class, it is also very suitable for reconstruction using the moving method. Isn't it meaningful to let the method go to its dream realm? If a method uses the functions of multiple classes, which class is more suitable for this method? A common practice is to determine which class has the data most used by this method, and then put this method together with those data. In this case, the time for moving a method is not to judge which class calls more, but to determine which class provides more data, which is different from the reconstruction instance.