Re: What is the best way to check a function's postcondition?
On Feb 22, 7:16 pm, Howard Hinnant <howard.hinn...@gmail.com> wrote:
Given a function:
Y f(X a)
{
Y y(a);
// do some computations
return y;
}
What is the best way to introduce a postcondition to ensure, at least
in debug builds, that the correct value of y is returned?
I typically see:
Y f(X a)
{
Y y(a);
// do some computations
assert(y has correct properties);
return y;
}
But more recently I've seen:
class Checker
{
Y& y_;
public:
Checker(Y& y);
~Checker()
{
assert(y_ has correct properties);
}
};
Y f(X a)
{
Y y(a);
Checker c(y);
// do some computations
return y;
}
Which idiom should be preferred and why? Which idiom is currently
used in practice?
I've only seen the first. The second seems very, very verbose.
Of course, the first only works if you restrict return to the
last statement of the function. But people I've seen who use
post-conditions have been concerned with program correctness
in general, using static analysis as well. And static analysis
is much easier when SESE is used, so they tend to use it as
well. Which automatically results in a single return, at the
end of the function. (Also, people not using SESE usually don't
have a variable to be returned.)
Another argument in favor of the second style is that it can be
modified to support a functional style of programming:
class Checker
{
Y myY;
public:
Checker(Y const& y) : myY(y) {}
~Checker() { /* the asserts */ }
operator Y() const { return myY; }
};
Y f(X a)
{
return Checker(expressionCreatingY);
}
I've not actually seen this used, but it looks tempting (albeit
still too verbose---you'd want a code generator or
a preprocessor to do it). At least to me---I frequently do use
a somewhat functional style. (Functional programs lend
themselves even more to static analysis than SESE---there's no
state to worry about.)
--
James Kanze
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]