• 重构2-Move Method(方法移动)


    重构同样非常简单,以至于人们并不认为这是一个有价值的重构。迁移方法(Move Method),顾名思义就是将方法迁移到合适的位置。在开始重构前,我们先看看一下代码:

    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;
    }
    }
    }
    这里值得注意的是BankAccount.CalculateInterest方法。当一个方法被其他类使用比在它所在类中的使用还要频繁时,我们就需要使用迁移方法重构了——将方法迁移到更频繁地使用它的类中。由于依赖关系,该重构并不能应用于所有实例,但人们还是经常低估它的价值。 最终的代码应该是这样的:
    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 class AccountInterest {
    public BankAccount Accountm{ get; private set ; }
    public AccountInterest(BankAccount account) {
    Account = account;
    }

    public double InterestRate {
    get {
    return CalculateInterestRate();
    }
    }
    public bool IntroductoryRate {
    get {
    return CalculateInterestRate() < 0.05;
    }
    }

    public double CalculateInterestRate() {
    if (Account.CreditScore > 800) return 0.02;
    if (Account.AccountAge > 10) return 0.03;
    return 0.05;
    }
    }
    简单吧。。
     
     





  • 相关阅读:
    3.5缺少动态连接库.so--cannot open shared object file: No such file or directory
    PHP中的变量详解
    Python类的实例属性详解
    Docker中的镜像分层技术详解
    如何编写优雅的代码?
    Node.js在不同平台的安装方法步骤详解
    Python3.X新特性之print和exec
    Django中如何配置Database缓存?
    Ajax中eval的使用详解
    如何创建和使用XMLHttpRequest对象?
  • 原文地址:https://www.cnblogs.com/jgig11/p/5784559.html
Copyright © 2020-2023  润新知