在C++中重构代码

Refactoring code in C++

本文关键字:代码 重构 C++      更新时间:2023-10-16

类路由的构造函数最初包含以下代码,用于检查文件中是否存在元素("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;
}