GotW #100: Preconditions, Part 1 (Difficulty: 8/10)
This special Guru of the Week series focuses on contracts. We’ve seen how postconditions are directly related to assertions (see GotWs #97 and #99). So are preconditions, but that in one important way makes them fundamentally different. What is that? And why would having language support benefit us even more for writing preconditions more than … Continue reading GotW #100: Preconditions, Part 1 (Difficulty: 8/10) →
This special Guru of the Week series focuses on contracts. We’ve seen how postconditions are directly related to assertions (see GotWs #97 and #99). So are preconditions, but that in one important way makes them fundamentally different. What is that? And why would having language support benefit us even more for writing preconditions more than for the other two?
JG Question
1. What is a precondition, and how is it related to an assertion? Explain your answer using the following example, which uses a variation of a proposed post-C++20 syntax for preconditions. [1]
// A precondition along the lines proposed in [1]
void f( int min, int max )
[[pre( min <= max )]]
{
// ...
}
Guru Questions
2. Rewrite the example in Question 1 to show how to approximate the same effect using assertions in today’s C++. Are there any drawbacks to your solution compared to having language support for preconditions?
3. If a precondition fails, what does that indicate, and who is responsible for fixing the failure? Explain how this makes a precondition fundamentally different from every other kind of contract.
4. Consider this example, expanded from a suggestion by Gábor Horváth:
auto calc( std::vector const& x ,
std::floating_point auto y ) -> double
[[pre( x[0] <= std::sqrt(y) )]] ;
Note that std::floating_point
is a C++20 concept.
- What kinds of preconditions must a caller of
calc
satisfy that can’t generally be written as testable boolean expressions? - What kinds of boolean-testable preconditions are implicit within the explicitly written declaration of
calc
? - Should any of these boolean-testable implicit preconditions also be written explicitly here in this precondition code? Explain.
Notes
[1] G. Dos Reis, J. D. Garcia, J. Lakos, A. Meredith, N. Myers, and B. Stroustrup. “P0542: Support for contract based programming in C++” (WG21 paper, June 2018). Subsequent EWG discussion favored changing “expects” to “pre” and “ensures” to “post,” and to keep it as legal compilable (if unenforced) C++20 for this article I also modified the syntax from : to ( ). That’s not a statement of preference, it’s just so the examples can compile today to make them easier to check.