《重构:改善既有代码的设计》 在对象之间搬移特性 之 2

版权声明:请注明转发出处 https://blog.csdn.net/mafucun1988/article/details/89372066

《重构:改善既有代码的设计》中提到过很多重构方法,关于在对象之间搬移特性的方法有9种。本文介绍:
搬移字段 move field

  • 名称: 搬移字段 move field
  • 概要:在目标类新建一个字段,修改源字段的所有用户,令它们改用新字段。
  • 动机: 在程序中,有个字段被其所驻类之外的另一个类更多的用到。

  • 做法:
    • 如果字段的访问级别是public,使用encapsulate field将它封装起来
    • 编译,测试
    • 在目标类中建立与源字段相同的字段,并同时建立相应的设值/取值函数
    • 编译目标类
    • 决定如何从源函数正确引用目标对象。如果有现成的字段或者函数能够取得目标对象,如果没有,就建立一个。如果还是不行,就在源类中新建一个字段来保存目标对象。
    • 删除源字段
    • 将所有对源字段的引用替换为对某个目标函数的调用。如果需要读取该变量,调用目标类的取值函数。如果需要设置该变量,调用目标类的设值函数。
    • 编译,测试
  • 代码演示

修改之前的代码:

///////////////////////////.h
#ifndef REFACTORMOVE_H
#define REFACTORMOVE_H

class AccountType
{
public:
    bool isPremium();
    double overdraftCharge(int daysOverdrawn);
private:
    int m_type;
};
class Account
{
public:
//   double overdraftCharge();
   double bankCharge();
   double interestForAmount_days(double amount, int days);
private:
   AccountType m_type;
   int m_daysOverdrawn;
   double m_interestRate;
};


#endif // REFACTORMOVE_H



///////////////////////////.cpp
#include "RefactorMove.h"

double Account::interestForAmount_days(double amount, int days)
{
    return m_interestRate *amount * days / 365;
}

我想要把m_interestRate搬移到AccountType类中。
修改之后的代码:

///////////////////////////.h
#ifndef REFACTORMOVE_H
#define REFACTORMOVE_H

class AccountType
{
public:
    bool isPremium();
    double overdraftCharge(int daysOverdrawn);
    void SetInterestRate(double interestRate);
    double GetInterestRate();

private:
    int m_type;
    double m_interestRate;
};
class Account
{
public:
    //   double overdraftCharge();
    double bankCharge();
    double interestForAmount_days(double amount, int days);
private:
    AccountType m_type;
    int m_daysOverdrawn;
    //double m_interestRate;
};


#endif // REFACTORMOVE_H

///////////////////////////.cpp
double Account::interestForAmount_days(double amount, int days)
{
    return m_type.GetInterestRate() *amount * days / 365;
}
void AccountType::SetInterestRate(double interestRate)
{
    m_interestRate = interestRate;
}

double AccountType::GetInterestRate()
{
    return m_interestRate;
}

如果源类中有很多函数已经使用了m_interestRate,可以先运用self encapsulate field. 给m_interestRate增加取值/设值函数。

猜你喜欢

转载自blog.csdn.net/mafucun1988/article/details/89372066