《重构:改善既有代码的设计》中提到过很多重构方法,关于重新组织数据的方法有16种。本文介绍:
以数据类取代记录 replace record with data class
- 名称:以数据类取代记录 replace record with data class
- 概要:为记录机构创建一个“哑”数据对象
- 动机:比如处理从数据库读出的记录,直接访问会造成数据暴露。有必要创建一个接口类,用来专门处理这些数据。
- 做法:
- 新建一个类,表示这个记录
- 对于记录中的每一项数据,在新建的类中建立对应的一个private字段,并提供相应的设值/取值函数
- 代码演示
修改之前的代码:
//从数据库中读出的数据
int height = 190;
int weight = 85;
修改之后的代码:
/DatabaseInterface.h
class DatabaseInterface
{
public:
int getHeight() const;
void setHeight(int Height);
int getWeight() const;
void setWeight(int Weight);
private:
int m_Height;
int m_Weight;
};
/DatabaseInterface.cpp
int DatabaseInterface::getHeight() const
{
return m_Height;
}
void DatabaseInterface::setHeight(int Height)
{
m_Height = Height;
}
int DatabaseInterface::getWeight() const
{
return m_Weight;
}
void DatabaseInterface::setWeight(int Weight)
{
m_Weight = Weight;
}
/main.cpp
DatabaseInterface dbi;
dbi.setHeight(190);
dbi.setWeight(85);
qDebug() << "Height = " << dbi.getHeight();
qDebug() << "Weight = " << dbi.getWeight();