【问题标题】:Refactoring code in C++ [closed]在 C++ 中重构代码 [关闭]
【发布时间】:2017-08-23 17:07:58
【问题描述】:

类路由的构造函数最初包含以下代码,用于检查文件中是否存在元素(“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 是做什么的?
  • 没有必要返回 void 函数 :) 但这里的问题出在其他地方。
  • 你能告诉我们你是如何以及在哪里执行你的新功能的吗?
  • 在您修改后的函数中,您不会打印到oss 同样的事情:“否”之后没有空格(除非type 以空格开头,我对此表示怀疑)。不知道这是否是问题所在,这真的取决于你用它做什么,但它可能是。
  • 我试图返回对 x。然后设置constructorReport = x.first和constructorSucceeded = x.second的值。

标签: c++ refactoring gpx


【解决方案1】:

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

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

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

【讨论】:

  • 我知道我哪里出错了。代码运行良好,我只需要省略 !调用它时。感谢您的帮助!。
猜你喜欢
  • 1970-01-01
  • 2010-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多