This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed. Find sources: "Design by contract" – news ·newspapers ·books ·scholar ·JSTOR(July 2025) (Learn how and when to remove this message) |

Design by contract (DbC), also known ascontract programming,programming by contract anddesign-by-contract programming, is an approach fordesigning software.
It prescribes that software designers should defineformal, precise and verifiable interface specifications forsoftware components, which extend the ordinary definition ofabstract data types withpreconditions,postconditions andinvariants. These specifications are referred to as "contracts", in accordance with aconceptual metaphor with the conditions and obligations of business contracts.
The DbC approachassumes allclient components that invoke an operation on aserver component will meet the preconditions specified as required for that operation.
Where this assumption is considered too risky (as in multi-channel ordistributed computing), theinverse approach is taken, meaning that theserver component tests that all relevant preconditions hold true (before, or while, processing theclient component's request) and replies with a suitable error message if not.
The term was coined byBertrand Meyer in connection with his design of theEiffel programming language and first described in various articles starting in 1986[1][2][3] and the two successive editions (1988, 1997) of his bookObject-Oriented Software Construction. Eiffel Software applied for trademark registration forDesign by Contract in December 2003, and it was granted in December 2004.[4][5] The current owner of this trademark is Eiffel Software.[6][7]
Design by contract has its roots in work onformal verification,formal specification andHoare logic. The original contributions include:
The central idea of DbC is a metaphor on how elements of a software system collaborate with each other on the basis of mutualobligations andbenefits. The metaphor comes from business life, where a "client" and a "supplier" agree on a "contract" that defines, for example, that:
Similarly, if themethod of aclass inobject-oriented programming provides a certain functionality, it may:
The contract is semantically equivalent to aHoare triple which formalises the obligations. This can be summarised by the "three questions" that the designer must repeatedly answer in the contract:
Manyprogramming languages have facilities to makeassertions like these. However, DbC considers these contracts to be so crucial tosoftware correctness that they should be part of the design process. In effect, DbC advocateswriting the assertions first.[citation needed] Contracts can be written bycode comments, enforced by atest suite, or both, even if there is no special language support for contracts.
The notion of a contract extends down to the method/procedure level; the contract for each method will normally contain the following pieces of information:[citation needed]
Subclasses in aninheritance hierarchy are allowed to weaken preconditions (but not strengthen them) and strengthen postconditions and invariants (but not weaken them). These rules approximatebehavioural subtyping.
All class relationships are between client classes and supplier classes. A client class is obliged to make calls to supplier features where the resulting state of the supplier is not violated by the client call. Subsequently, the supplier is obliged to provide a return state and data that does not violate the state requirements of the client.
For instance, a supplier data buffer may require that data is present in the buffer when a delete feature is called. Subsequently, the supplier guarantees to the client that when a delete feature finishes its work, the data item will, indeed, be deleted from the buffer. Other design contracts are concepts ofclass invariant. The class invariant guarantees (for the local class) that the state of the class will be maintained within specified tolerances at the end of each feature execution.
When using contracts, a supplier will verify that the contract conditions are satisfied—a practice known asoffensive programming—the general idea being that code should "fail hard", with contract verification being the safety net.
DbC's "fail hard" property simplifies the debugging of contract behavior, as the intended behaviour of each method is clearly specified.
This approach differs substantially from that ofdefensive programming, where the supplier is responsible for figuring out what to do when a precondition is broken. More often than not, the supplier throws an exception to inform the client that the precondition has been broken, and in both cases—DbC and defensive programming alike—the client must figure out how to respond to that. In such cases, DbC makes the supplier's job easier.
Design by contract also defines criteria for correctness for a software module:
Design by contract can also facilitate code reuse, since the contract for each piece of code is fully documented. The contracts for a module can be regarded as a form ofsoftware documentation for the behavior of that module.
Design by contract may look something like this:[8][9]
intf(constintx)pre(x!=1)// a precondition assertionpost(r:r==x&&r!=2)// a postcondition assertion; r names the result object of f{contract_assert(x!=3);// an assertion statementreturnx;}
Contract conditions should never be violated during execution of a bug-free program. Contracts are therefore typically only checked in debug mode during software development. Later at release, the contract checks are disabled to maximize performance.
In many programming languages, contracts are implemented withassert. Asserts are by default compiled away in release mode in C/C++, and similarly deactivated in C#[10] and Java.
Launching the Python interpreter with "-O" (for "optimize") as an argument will likewise cause the Python code generator to not emit any bytecode for asserts.[11]
This effectively eliminates the run-time costs of asserts in production code—irrespective of the number and computational expense of asserts used in development—as no such instructions will be included in production by the compiler.
Design by contract does not replace regular testing strategies, such asunit testing,integration testing andsystem testing. Rather, it complements external testing with internal self-tests that can be activated both for isolated tests and in production code during a test-phase.
The advantage of internal self-tests is that they can detect errors before they manifest themselves as invalid results observed by the client. This leads to earlier and more specific error detection.
The use of assertions can be considered to be a form oftest oracle, a way of testing the design by contract implementation.
Languages that implement most DbC features natively include:
Additionally, the standard method combination in theCommon Lisp Object System has the method qualifiers:before,:after and:around that allow writing contracts as auxiliary methods, among other uses.
{{cite web}}: CS1 maint: multiple names: authors list (link)