zoukankan      html  css  js  c++  java
  • 重构:Move Method 笔记

    重构:Move Method

               Move Method就是将方法迁移到合适的位置。

               条件:当一个方法被其他类使用比在它所在类中的使用还要频繁时,我们就需要将方法迁移到更频繁地使用它的类中(Move Method重构)

               范例如下:

    修改前代码
      public class BankAccount
        {
            
    public BankAccount(int accountNum)
            {
                AccountNum 
    = accountNum;
            }
            
    public int AccountNum { getprivate set; }
          
      public double CalculateInterestRate()
            {
                
    if (AccountNum > 800)
                    
    return 0.02;
                
    if (AccountNum > 10&&AccountNum<=800)
                    
    return 0.03;
                
    return 0.05;
            }
        }

        
    public class AccountInterest
        {
            
    public BankAccount Account { getprivate set; }
            
    public AccountInterest(BankAccount account)
            {
                Account 
    = account;
            }
            
    public double InterestRate
            {
                
    get { return Account.CalculateInterestRate(); }

            }
            
    public bool IntroductoryRate
            {
                
    get { return Account.CalculateInterestRate() < 0.05; }
            }

        }

          发现后者比前者使用标注中的方法的频率更高,因此将该方法移动至后者中。 

          修改后代码:

    修改后代码
        public class BankAccount
        {
            
    public BankAccount(int accountNum)
            {
                AccountNum 
    = accountNum;     
            }
            
    public int AccountNum { getprivate set; }
        }
        
    public class AccountInterest
        {
            
    public BankAccount Account { getprivate 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.AccountNum > 800)
                    
    return 0.02;
                
    if (Account.AccountNum > 10 && Account.AccountNum <= 800)
                    
    return 0.03;
                
    return 0.05;
            }
        }

          代码操作更加清晰,直观。功能单一化。

  • 相关阅读:
    Windows系统开机硬盘自检问题解决
    更改软件默认安装路径
    windows添加开机启动项
    xp 如何打开(进行)远程桌面连接
    xp看系统位数
    教你创建一个别人打不开删不掉的文件夹(干坏事爱好者必看)
    无操作一段时间显示器无信号
    长时间用电脑,(给窗口选一个合适的颜色)设置窗口绿色
    Windows右键菜单设置与应用技巧
    Outlook如何定时发邮件
  • 原文地址:https://www.cnblogs.com/jasenkin/p/1799382.html
Copyright © 2011-2022 走看看