What are preconditions and postconditions?

Simon J picture Simon J · Feb 9, 2016 · Viewed 11.9k times · Source

I'm learning how to program but one thing I can't quite get my head around is preconditions and postconditions.

Is an if statement before calling a function considered a precondition, or is there a separate more efficient way of doing this in most languages?

I'm also struggling to find any examples of preconditions that I could understand with my current knowledge of programming if anyone could prove a simple one then I would really appreciate it (any language will be fine)

Answer

陳 力 picture 陳 力 · Jun 9, 2018

It is well-stated in this c++'s paper

  • A precondition is a predicate that should hold upon entry into a function. It expresses a function's expectation on its arguments and/or the state of objects that may be used by the function.

  • A postcondition is a predicate that should hold upon exit from a function. It expresses the conditions that a function should ensure for the return value and/or the state of objects that may be used by the function.


Preconditions and postconditions belong to Contract-based-programming.

In Dlang, Contract-based-programming have good designs. This document offers a sample:

long square_root(long x)
in
{
    assert(x >= 0);
}
out (result)
{
    assert(result ^^ 2 <= x && (result + 1) ^^ 2 > x);
}
do
{
    return cast(long)std.math.sqrt(cast(real)x);
}

Preconditions are in in block, postconditions are in out block.

  • If preconditions and postconditions are satisfied, then it will compile happily, like passing 9 into the function. live demo
  • If preconditions are not satisfied, like passing -1 into the function. live demo

    [email protected](8): Assertion failure

  • If postconditions are not satisfied which can be caused by we didn't deal with the logic in the do block, like return square rather than square-root, then, postconditions will work: live demo

    [email protected](13): Assertion failure

For class, Dlang also has good tools, read the document to learn more


BTW, c++ also lists contract design into c++20's draft: https://www.reddit.com/r/cpp/comments/8prqzm/2018_rapperswil_iso_c_committee_trip_report/

Here is the proposal, maybe also helpful to understand them(though, much ugly than D, IMHO)