Disclaimer
I'm not entirely sure if this is the right SE for this, but I'll start here anyway.
Background
I was reading this question earlier and was looking at this code snippet in one of the answers
auto z = [&](){ static auto cache_x = x;
static auto cache_y = y;
static auto cache_result = x + y;
if (x == cache_x && y == cache_y)
return cache_result;
else
{
cache_x = x;
cache_y = y;
cache_result = x + y;
return cache_result;
}
};
Personally, I would be inclined to rewrite it as follows, with a single return statement
auto z = [&](){ static auto cache_x = x;
static auto cache_y = y;
static auto cache_result = x + y;
if (x == cache_x && y == cache_y)
{
}
else
{
cache_x = x;
cache_y = y;
cache_result = x + y;
}
return cache_result;
};
but this leaves a blank body for the if
part.
We could rewrite the if/else
to just be if(!(x == cache_x && y == cache_y))
but this runs the risk of being misunderstood (and can get messy).
My Question
What is the more accepted way of writing something like this, should we
- have multiple return statements
- leave the body of the
if
blank - rewrite the
if
condition to be the negated version - something else
Please note, I usually code in Java whereas the sample code is in C++. I am interested in the generally accepted way of doing things, as opposed to specific C++ constructs/methods.
Aucun commentaire:
Enregistrer un commentaire