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).
In DbC, every software component is treated as a contract party with certain obligations and guarantees:
Preconditions
Conditions that must be true before a method or function can execute correctly.
→ Responsibility of the caller.
Postconditions
Conditions that must be true after the execution of a method or function.
→ Responsibility of the method/function.
Invariant (Class Invariant)
Conditions that must always remain true throughout the lifetime of an object.
→ Responsibility of both the method and the caller.
Clear specification of responsibilities.
More robust and testable software.
Errors are detected early (e.g., through contract violations).
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
}
}
Clear contracts reduce misunderstandings.
Easier debugging, as violations are detected immediately.
Supports defensive programming.
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).