When writing code that contains repeated blocks, it is good practice to extract it in an outside function.
C++11 also allows me to extract the code into a lambda, within the function body. Are there any hidden pitfalls to this?
Should I always use external functions, or is it preferable to use lambdas?
Example:
using namespace std;
void to_refactor(const somedata& data)
{
if (data.has_some_failed_condition())
{
ostringstream buffer;
buffer << "to_refactor: " << data.name;
buffer << ": " << data.details() << ".";
throw runtime_error(buffer.str());
}
if (other_failed_condition())
{
ostringstream buffer;
buffer << "to_refactor: " << data.name;
buffer << ": other_failed_condition.";
throw runtime_error(buffer.str());
}
// more stuff
}
Refactoring:
void to_refactor(const somedata& data)
{
auto throw_runtime_error =
[](const string& name, const string& message)
{
ostringstream buffer;
buffer << "to_refactor: " << name;
buffer << ": " << message << ".";
throw std::runtime_error(buffer.str());
};
if (data.has_some_failed_condition())
throw_runtime_error(data.name(), data.details());
if (other_failed_condition())
throw_runtime_error(data.name(), "other_failed_condition");
// more stuff
}
TLDR: In the code above, I would have normally ("normally"="before C++11") extracted throw_runtime_error as a function outside of to_refactor. Are there hidden pitfalls to keeping it as a lambda? Is it a good/better practice than using external functions?