版权声明:请注明转发出处 https://blog.csdn.net/mafucun1988/article/details/89349763
《重构:改善既有代码的设计》中提到过很多重构方法,关于重新组织函数的方法有9种。本文介绍:
提炼函数 Extract method
- 名称:提炼函数 Extract method
- 概要:有一段代码可以被组织在一起并独立出来。将这段代码放进一个独立函数中,并让函数名称解释该函数的用途
- 动机:每个函数的粒度越小,被复用的机会就会越多
- 做法:
- 创造一个新函数,根据函数用来“做什么”来命名,而不是以“怎么做”命名
- 将提炼出的代码从源函数复制到新建的目标函数中
- 查看局部变量和源函数参数是否引用了“作用域限于源函数”
- 查看是否有仅用于被提炼代码段的临时变量,在目标函数中将其声明为临时变量
- 查看是否有任何源函数的局部变量值被它改变。如果有一个,可以作为返回值。如果有多个,可以先使用split temporary variable,然后再尝试提炼。也可以使用replace temp with query将临时变量消灭掉。
- 将被提炼代码段中需要读取的局部变量,当作参数传给目标函数
- 处理完所有局部变量之后,进行编译
- 在源函数中,将被提炼代码段替换为对目标函数的调用。
- 删除源函数中临时变量的声明。
- 编译测试
- 代码演示
修改之前的代码:
///////////////////////////.h
#ifndef REFACTORMETHOD_H
#define REFACTORMETHOD_H
#include <QString>
#include <QVector>
class RefactorMethod
{
public:
RefactorMethod(QString name);
void PrintOwing(double amount);
private:
QString m_Name;
QVector<double> m_Order;
};
#endif // REFACTORMETHOD_H
///////////////////////////.cpp
#include "RefactorMethod.h"
#include <QDebug>
RefactorMethod::RefactorMethod(QString name)
{
m_Name = name;
}
void RefactorMethod::PrintOwing(double amount)
{
double outstanding = amount * 1.2;
//print banner
qDebug() << "**********************" << m_Name;
qDebug() << "****customer owes*****" << m_Name;
qDebug() << "**********************" << m_Name;
//calculate outstanding
for (double e : m_Order)
{
outstanding += e;
}
//print detail
qDebug() << "name = " << m_Name;
qDebug() << "amount = " << amount;
}
修改之后的代码:
///////////////////////////.h
#ifndef REFACTORMETHOD_H
#define REFACTORMETHOD_H
#include <QString>
#include <QVector>
class RefactorMethod
{
public:
RefactorMethod(QString name);
void PrintOwing(double amount);
void PrintDetails(double amount);
void PrintBanner();
double GetOutstanding(double initValue);
private:
QString m_Name;
QVector<double> m_Order;
};
#endif // REFACTORMETHOD_H
///////////////////////////.cpp
#include "RefactorMethod.h"
#include <QDebug>
RefactorMethod::RefactorMethod(QString name)
{
m_Name = name;
}
void RefactorMethod::PrintOwing(double amount)
{
//对局部变量再赋值
double outstanding = amount * 1.2;
outstanding = GetOutstanding(outstanding);
//无局部变量
PrintBanner();
//有局部变量
PrintDetails(amount);
}
void RefactorMethod::PrintDetails(double amount)
{
qDebug() << "name = " << m_Name;
qDebug() << "amount = " << amount;
}
void RefactorMethod::PrintBanner()
{
//print banner
qDebug() << "**********************" << m_Name;
qDebug() << "****customer owes*****" << m_Name;
qDebug() << "**********************" << m_Name;
}
//input: initValue
//output: result
double RefactorMethod::GetOutstanding(double initValue)
{
double result = initValue;
for (double e : m_Order)
{
result += e;
}
return result;
}