mercredi 27 avril 2016

Is there drawbacks to use C++11 lambdba and macro for error handling?

Hello,

Properly testing function return values is fundamental, but it can quickly clutter the code and make it hard to read, like in the simple example below:

#include <iostream>
#include <fstream>

int main(int argc, char **argv) 
{
  std::string filename("/usr/include/malloc.h");
  std::ifstream ifs(filename.c_str());
  if (!ifs.is_open())
  {
    std::cerr << "Failed to open file " << filename << std::endl;
    return 1;
  }
  ifs.close();
  std::cout << "Passed the first error handling" << std::endl;

  filename = "/this/file/does/not/exist";
  ifs.open(filename.c_str());
  if (!ifs.is_open())
  {
    std::cerr << "Failed to open file " << filename << std::endl;
    return 1;
  }
  return 0;
}

I have thought of a solution reducing cluttering by using a macro and c++11 lambda functions like that:

#include <iostream>
#include <fstream>

#define RETURN_IF(X,Y,Z) if ( X ) { Y ; return Z; }

auto open_file_error = [](const std::string& filename)
{
  std::cerr << "Failed to open file " << filename << std::endl;
};


int main(int argc, char **argv) 
{
  std::string filename("/usr/include/malloc.h");
  std::ifstream ifs(filename.c_str());
  RETURN_IF (!ifs.is_open(), open_file_error(filename), 1 );
  ifs.close();
  std::cout << "Passed the first error handling" << std::endl;

  filename = "/this/file/does/not/exist";
  ifs.open(filename.c_str());
  RETURN_IF (!ifs.is_open(), open_file_error(filename), 1 );
  return 0;
}

As you can see, the main function is less cluttered. Do you think that there is drawbacks to doing like that or could it be a method to largely use ?

Note that I use several macros to handle cases with or without a return value, for testing equality with a value, etc.

Aucun commentaire:

Enregistrer un commentaire