bg_image
header

Design by Contract - DbC

Design by Contract (DbC) is a concept in software development introduced by Bertrand Meyer. It describes a method to ensure the correctness and reliability of software by defining clear "contracts" between different components (e.g., methods, classes).

Core Principles of Design by Contract

In DbC, every software component is treated as a contract party with certain obligations and guarantees:

  1. Preconditions
    Conditions that must be true before a method or function can execute correctly.
    → Responsibility of the caller.

  2. Postconditions
    Conditions that must be true after the execution of a method or function.
    → Responsibility of the method/function.

  3. Invariant (Class Invariant)
    Conditions that must always remain true throughout the lifetime of an object.
    → Responsibility of both the method and the caller.

Goal of Design by Contract

  • Clear specification of responsibilities.

  • More robust and testable software.

  • Errors are detected early (e.g., through contract violations).

Example in Pseudocode

class BankAccount {
    private double balance;

    // Invariant: balance >= 0

    void withdraw(double amount) {
        // Precondition: amount > 0 && amount <= balance
        if (amount <= 0 || amount > balance) throw new IllegalArgumentException();

        balance -= amount;

        // Postcondition: balance has been reduced by amount
    }
}

Benefits

  • Clear contracts reduce misunderstandings.

  • Easier debugging, as violations are detected immediately.

  • Supports defensive programming.

Drawbacks

  • Requires extra effort to define contracts.

  • Not directly supported by all programming languages (e.g., Java and C++ via assertions, Python with decorators; Eiffel supports DbC natively).