移动方法

本文介绍了一种常见的重构方法——移动方法。通过将方法从一个类移动到另一个更合适的类,可以使代码职责更加清晰,提高代码的可维护性。文章通过银行账户利率计算的例子详细展示了移动方法的具体操作。

概念:本文所讲的移动方法就是方法放在合适的位置(通常指放在合适的类中)。

 

正文:移动方法是一个非常easy也非经常见的重构。仅仅要是系统就会存在非常多类,那么类里面包含非常多方法,假设一个方法经常被另外一个类使用(比本身的类使用还多)或者这种方法本身就不应该放在这个类里面,那么这个适合应该考虑把它移到合适的类中。代码例如以下:

namespace LosTechies.DaysOfRefactoring.MoveMethod.Before
{
    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类的职责也单一。同一时候CalculateInterestRate也放到了常常使用且适合它的类中了。所以此重构是一个比較好的重构,能让整个代码变得更加合理。

namespace LosTechies.DaysOfRefactoring.MoveMethod.After
{
    public class AccountInterest
    {
        public BankAccount Account { 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;
        }
    }
}

namespace LosTechies.DaysOfRefactoring.MoveMethod.After
{
    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; }
    }
}

总结:这个重构法则在非常多时候能让我们把代码组织的结构调整得更合理,同一时候也能给以后的维护带来方便。

转载于:https://www.cnblogs.com/gavanwanggw/p/6708891.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值