Design by Contract.


Design by Contract is the Software Collaboration Method.

Contract (between class user and class author) should state under which condition class will provide it's services to class user.


There are preconditions, postconditions and invariants that regulate contract.

Precondition is a condition that is required for something to happen. Precondition can be simple or complex, complex precondition consists of multiple simple or complex preconditions as well.

Postcondition is something that is guaranteed to happen if preconditions are met & program behaves correctly.

Invariants is something that is guaranteed to hold, at least in observable moments in time, or perhaps even all the time.

If class user provides 'correct' (or using alternative wording: 'legal') preconditions to object, methods will ensure that postconditions are met. Invariants are always met (though some disagree, for there's 'observable moment' argument), or contract is broken.

Examples for Preconditions:

- method arguments,
- concurrency requirements,
- perhaps more.

Examples for Postconditions:

- program's process(-es) will compute and provide results correctly,
- program will finish within the agreed time frame in at least 90% of situations,
- perhaps more.

Examples for Invariants:

- heat in Reactor will never go above the Critical Value,
- variable 'divisor' will never have '0' value,
- variable 'divisor' will never have '0' value during computations phase,
- perhaps more.

Inheritance (in simple words).

To not break contract, following conditions must be met:

1. subclasses must require no more than it's neccessary for superclass to work correctly (but can require less).

2. subclasses must meet all requirements of superclass (but perhaps can give more).

This is related with the Liskov's Substitution Principle (LSP).

Exceptions in Java.

When contract is broken during Runtime, an Exception should be thrown.

See also: SOLID, Conditions, Security Harness, Software Complexity, Application Design, Use Cases & Automatic Testing.


  1. this way tests can be automated.

  2. credits: Eiffel Programming Language.

  3. perhaps it can be combined with Petri Net alike concurrency. i'll check and perhaps use.

  4. (EN) Precondition = (PL) Warunek wstępny, Warunek początkowy.
    (EN) Postcondition = (PL) Warunek końcowy.
    (EN) Invariant = (PL) Niezmiennik.

  5. there are uses for excess safety measures...

    for example, we can attempt to guard Reactor from being overheated, but temperature depends not only on software. if external source heats Reactor, we can see exception, report in log file and/or on screen and employ exception handling in attempt to reduce the heat.