移动方法(Move Method)是指把类中的方法移动到更加合适、合理的地方,特别是当该方法放在其他类中会比放在原来的类中更加经常被调用的时候。下面的代码例子:
- class BankAccount {
- private int accountAge;
- private int creditScore;
- private double interest;
- public int getAccountAge() {
- return accountAge;
- }
- public void setAccountAge(int accountAge) {
- this.accountAge = accountAge;
- }
- public int getCreditScore() {
- return creditScore;
- }
- public void setCreditScore(int creditScore) {
- this.creditScore = creditScore;
- }
- public double getInterest() {
- return interest;
- }
- public void setInterest(double interest) {
- this.interest = interest;
- }
- public BankAccount(int accountAge, int creditScore, double interest) {
- this.accountAge = accountAge;
- this.creditScore = creditScore;
- this.interest = interest;
- }
- // 计算利率
- public double calculateInteresRate() {
- if(creditScore > 500) {
- return 0.02;
- }else if(accountAge > 10) {
- return 0.03;
- }
- return 0.05;
- }
- }
- class AccountInterest {
- private BankAccount account;
- public AccountInterest(BankAccount account) {
- this.account = account;
- }
- public double insterestRate(){
- return account.calculateInteresRate();
- }
- public boolean introductoryRate(){
- return (account.calculateInteresRate() < 0.05);
- }
- }
由于 AccountInterest 类比起 BankAccount 类更加频繁地调用计算利率的方法 calculateInteresRate() 。也就是说,该方法放置在 AccountInterest 类中更符合业务逻辑。那么重构的方式就是将 calculateInteresRate() 方法移动到 AccountInterest 类中即可,如下:
- class BankAccount {
- private int accountAge;
- private int creditScore;
- private double interest;
- public int getAccountAge() {
- return accountAge;
- }
- public void setAccountAge(int accountAge) {
- this.accountAge = accountAge;
- }
- public int getCreditScore() {
- return creditScore;
- }
- public void setCreditScore(int creditScore) {
- this.creditScore = creditScore;
- }
- public double getInterest() {
- return interest;
- }
- public void setInterest(double interest) {
- this.interest = interest;
- }
- public BankAccount(int accountAge, int creditScore, double interest) {
- this.accountAge = accountAge;
- this.creditScore = creditScore;
- this.interest = interest;
- }
- }
- class AccountInterest {
- private BankAccount account;
- public AccountInterest(BankAccount account) {
- this.account = account;
- }
- public double insterestRate(){
- return account.calculateInteresRate();
- }
- public boolean introductoryRate(){
- return (account.calculateInteresRate() < 0.05);
- }
- // 计算利率
- public double calculateInteresRate() {
- if(account.getCreditScore() > 500) {
- return 0.02;
- }else if(account.getAccountAge() > 10) {
- return 0.03;
- }
- return 0.05;
- }
- }
看起来很简单的一种重构方法,就是“移动”,把一段方法代码移动到更加合适的地方。但是这并不容易做到,因为我们要判断到底哪个方法处于哪个类中才更合适,这个评判、衡量的尺度怎样把握,并不容易做到。此外,我认为虽然方法移动了,但是最终调用的时候还是通过原来类的对象来作为条件语句中的判断,也是依赖了原来的类,上面例子中的account.getCreditScore() > 500 和 account.getAccountAge() > 10 就是这样。只不判断之后的真正业务处理(计算利率)才由重构后的类来实现。
本文转自 xxxx66yyyy 51CTO博客,原文链接:http://blog.51cto.com/haolloyin/343524,如需转载请自行联系原作者