在C++中重构代码
Refactoring code in C++
类路由的构造函数最初包含以下代码,用于检查文件中是否存在元素("gpx"、"rte"等(。它应该运行。
if (! elementExists(source,"gpx"))
{
oss << endl << "no gpx tag";
constructorReport = oss.str();
constructorSucceeded = false;
return;
}
if (! elementExists(source,"rte"))
{
oss << endl << "no rte tag";
constructorReport = oss.str();
constructorSucceeded = false;
return;
}
我试图引入一个函数来替换这些 if 语句。程序构建正常。
void Route::constCheck(string source, string type)
{
if (! XML_Parser::elementExists(source, type))
{
std::ostringstream oss;
oss << std::endl << "no" << type <<" tag";
constructorReport = oss.str();
constructorSucceeded = false;
return;
}
}
我已经更改了 gpx 文件,它检查该文件以产生错误,但使用我添加的功能,它继续,就好像没有错误一样。
任何帮助不胜感激,如果您需要更多信息,请告诉我。我试图按照指南保持代码轻量级。
在原始代码中,当其中一个测试失败时,您从函数返回,您不会继续尝试其他测试。
现在,你已将测试移动到函数中,调用方无法知道测试是否失败,因此它将执行所有这些测试,并且当其中一个测试失败时永远不会从其函数返回。您需要此函数返回一个布尔值,指示它是否失败。
bool Route::constCheck(string source, string type)
{
if (! XML_Parser::elementExists(source, type))
{
std::ostringstream oss;
oss << std::endl << "no" << type <<" tag";
constructorReport = oss.str();
constructorSucceeded = false;
return false;
}
return true;
}
然后,原始代码的替换将如下所示:
if (!constCheck(source, "gpx")) {
return;
}
if (!constCheck(source, "rte")) {
return;
}
相关文章:
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 重构类:无法将派生类中成员函数的公共代码移回基类
- 重构此代码以进行优化
- 在C++中重构代码
- 将样本代码重构为类,并没有提高过载功能的实例
- 如何将此代码重构为多线程版本
- 使用OTool进行了重构代码的二进制比较
- 如何重构这个类模板以最小化锅炉板代码
- 函数参数已更改:如何重构代码,尽可能少
- 解开高德纳的结:如何重构意大利面条代码?
- 重构多线程方案的单线程 GUI 代码
- 重构代码以使用 Boost 共享指针
- 使用函数对象重构 C++ 代码
- 绘制游戏组件的重构代码
- 代码重构尝试使用多态性和std::map
- 如何重构C++代码以支持动态数组大小
- 有没有一种方法可以将C++11代码重构为C++代码,这些代码可以由能力较弱的编译器编译
- 重构常规c++代码模式
- 用c++中已有的类重构代码
- 如何重构这段简单的代码以避免代码重复