在 C++ 中重构代码

Refactoring code in C++

class 路由的构造函数最初包含以下代码,用于检查文件中是否存在元素("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 文件,它检查该文件以产生错误,但使用我添加的功能它继续运行,就好像没有错误一样。

感谢任何帮助,如果您需要更多信息,请告诉我。我试图按照指南保持代码简洁。

在您的原始代码中,您从函数 return 第一次测试失败时,您不会继续尝试其他测试。

现在您已将测试移至函数中,调用者无法知道测试是否失败,因此它将执行所有测试,并且永远不会 return 从其函数中执行一个他们失败了。您需要此函数来 return 一个指示它是否失败的布尔值。

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;
}