Finding a successful solution for processing errors



  • In the annex being developed, part of the classes are designed in such a way that the status of performance of the function is either returned or retained in the field concerned. These classes are related to the processing of files, xml documents, etc. After each operation, the status of implementation has to be verified, for example:

    if (xmlParser.hasError()) {
        log(...);
        return <ошибка выполнения>; // завершаем выполнение текущей функции, поскольку продолжать не имеет смысла.
    }
    

    These checks in the body can run quite a lot. In fact, the question is whether it is possible to reduce the code aimed at verifying the status of implementation and to focus on the logic of the function itself. Perhaps you'd better use the exceptions then? Or is the current solution viable?



  • Use the exceptions, they're specially designed for this purpose.

    Either, if you're wrong, you'. xmlParser to a state where he does nothing, and make a mistake once after all operations with him, as in standard input flows:

    void f(std::istream& s, int& a, int& b) {
      s >> a >> b;
      bool eof = !s;
      ...
    

    The current approach to the verification of errors is bad because it does not encourage or control that all errors will be verified. It's very easy not to write. if (xmlParser.hasError())or erroneously write if (!xmlParser.hasError())

    If mistakes are used, it is better to revert to a mistake from the very function that has been performed by the error:

    void parse(error_code& ec) {
      if (xmlParser.parse(ec))
        return;
    }
    

    or https://svn.boost.org/trac/boost/wiki/BestPracticeHandbook#a8.DESIGN:Stronglyconsiderusingconstexprsemanticwrappertransporttypestoreturnstatesfromfunctions (i.e. optional), which is a more modern approach, but unfortunately there are so far few libraries of practice. Result♪ http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4109.pdf etc.

    Result<void> result = xmlParser.parse();
    if (!result)
      return result.error();
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2