Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Exceptions and Contracts

Preconditions and Postconditions

Use Ada 2012 contracts: Pre and Post aspects, the 'Result and 'Old attributes, Contract_Cases, assertion policy and how contracts differ from exceptions, with C stand-ins.

A good subprogram is a small promise: "give me this, and I will give you that". Ada 2012 lets you write that promise in code. A precondition states what the caller must guarantee; a postcondition states what the subprogram guarantees in return. Together they are called a contract, and they are checked at run time when you enable assertions, or proved statically by tools such as SPARK (see What Is SPARK?).

The Ada code is read-only here (no compiler on the site), and the runnable examples are C stand-ins using assert-style macros.

Writing a contract

Contracts are attached to a subprogram declaration as aspects:

ADA
function Integer_Sqrt (N : Natural) return Natural
  with Post => Integer_Sqrt'Result ** 2 <= N
               and then (Integer_Sqrt'Result + 1) ** 2 > N;

procedure Withdraw (Balance : in out Natural; Amount : Natural)
  with Pre  => Amount <= Balance,
       Post => Balance = Balance'Old - Amount;
  • Pre is a Boolean expression over the parameters (and global state). It is the caller's responsibility. If it is false at the call, the contract is violated by the caller.
  • Post is checked when the subprogram returns normally. It is the subprogram's responsibility.
  • F'Result names the value returned by function F inside its own postcondition.
  • X'Old is the value X had on entry, so a postcondition can relate before and after.

When assertions are enabled (for GNAT, -gnata, or pragma Assertion_Policy (Check)), a failing Pre or Post raises Ada.Assertions.Assertion_Error. With assertions disabled, nothing is checked and no code is generated, so contracts cost nothing in a release build. The usual workflow: enable them in testing, prove them where it matters, and decide deliberately for production.

Contract at a glance

Pre caller must ensure
Post callee must ensure
'Old value on entry
'Result returned value

Contracts are executable documentation.

1 / 2

Contract_Cases

When a subprogram has several distinct behaviors, Contract_Cases states each as "guard => consequence":

ADA
function Sign (X : Integer) return Integer
  with Contract_Cases =>
    (X < 0  => Sign'Result = -1,
     X = 0  => Sign'Result =  0,
     X > 0  => Sign'Result =  1);

The guards must be disjoint and cover every case; the checker verifies both. It reads like a table of the specification.

Contracts versus exceptions

Beginners ask: should Withdraw raise an exception if the balance is too low, or have a precondition?

  • If a caller can check the condition first and a violation means a bug in the caller, use a precondition. The error is the caller's mistake and is caught in testing or proof.
  • If the condition depends on the outside world and cannot be known beforehand (the file may vanish, the network may drop), raise an exception, since a correct caller cannot avoid it.

For Withdraw, "amount at most balance" is checkable up front, so it is a precondition; the caller should have asked for the balance. A function whose job is to report such cases to a user might instead return a status value.

A precondition on a dispatching call or a subprogram in a package is part of its public contract, so putting it in the specification (not the body) makes it visible to callers and tools. Postconditions can mention only things visible in the specification; hide internal state through functions with expression bodies if needed.

Stand-in: contract macros (C, runnable)

C has no aspects, but you can model them with two macros. The program checks a precondition before and a postcondition after withdraw, and shows a violated precondition being reported. It uses a failure counter instead of aborting so you can see every case.

C C stand-in: Pre and Post as macros

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: a postcondition that catches a bug (C, runnable)

A postcondition is most valuable when it checks the meaning of the result, independent of how the code computes it. This integer square root has a deliberate off-by-one; the postcondition catches it for perfect squares only when the loop bound is wrong. Run it, then fix < to <= in your copy.

C C stand-in: a postcondition finds an off-by-one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The failing inputs are the perfect squares 1, 4, 9 and 16 (the bug returns one too few), and a contract like this reveals the bug without us having to know the expected values in advance.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who is responsible if a Pre aspect evaluates to False at a call?

    A precondition describes what the caller must guarantee.
  2. 2. What does Balance'Old mean inside a Post aspect?

    'Old lets a postcondition compare the final state with the entry state.
  3. 3. What happens to Pre and Post when assertions are disabled?

    Assertion policy controls whether contracts are checked at run time.
  4. 4. When should a failure be a raised exception rather than a precondition?

    Unavoidable external failures belong to exceptions; avoidable caller mistakes belong to contracts.

Summary

  • Pre states what the caller must ensure, Post what the subprogram ensures.
  • 'Old and 'Result relate postconditions to entry state and return value.
  • Contract_Cases expresses behaviors as disjoint guarded cases.
  • Contracts are checked when assertions are enabled, and can be proved with SPARK.
  • Use preconditions for avoidable caller mistakes and exceptions for unavoidable external failures.

Next: Type Invariants and Predicates