Design by contract
Design by contract, also known as contract programming, programming by contract and design-by-contract programming, is an approach for designing software.
It prescribes that software designers should define formal, precise and verifiable interface specifications for software components, which extend the ordinary definition of abstract data types with preconditions, postconditions and invariants. These specifications are referred to as "contracts", in accordance with a conceptual metaphor with the conditions and obligations of business contracts.
The DbC approach assumes all client components that invoke an operation on a server component will meet the preconditions specified as required for that operation.
Where this assumption is considered too risky the inverse approach is taken, meaning that the server component tests that all relevant preconditions hold true and replies with a suitable error message if not.
History
The term was coined by Bertrand Meyer in connection with his design of the Eiffel programming language and first described in various articles starting in 1986 and the two successive editions of his book Object-Oriented Software Construction. Eiffel Software applied for trademark registration for Design by Contract in December 2003, and it was granted in December 2004. The current owner of this trademark is Eiffel Software.Design by contract has its roots in work on formal verification, formal specification and Hoare logic. The original contributions include:
- A clear metaphor to guide the design process
- The application to inheritance, in particular a formalism for redefinition and dynamic binding
- The application to exception handling
- The connection with automatic software documentation
Description
- The supplier must provide a certain product and is entitled to expect that the client has paid its fee.
- The client must pay the fee and is entitled to get the product.
- Both parties must satisfy certain obligations, such as laws and regulations, applying to all contracts.
- Expect a certain condition to be guaranteed on entry by any client module that calls it: the method's precondition—an obligation for the client, and a benefit for the supplier, as it frees it from having to handle cases outside of the precondition.
- Guarantee a certain property on exit: the method's postcondition—an obligation for the supplier, and obviously a benefit for the client.
- Maintain a certain property, assumed on entry and guaranteed on exit: the class invariant.
- What does the contract expect?
- What does the contract guarantee?
- What does the contract maintain?
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:
- Acceptable and unacceptable input values or types, and their meanings
- Return values or types, and their meanings
- Error and exception condition values or types that can occur, and their meanings
- Side effects
- Preconditions
- Postconditions
- Invariants
- Performance guarantees, e.g. for time or space used
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 of class invariant. The class invariant guarantees that the state of the class will be maintained within specified tolerances at the end of each feature execution.
When using contracts, a supplier should not try to verify that the contract conditions are satisfied—a practice known as offensive 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 of defensive 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:
- If the class invariant AND precondition are true before a supplier is called by a client, then the invariant AND the postcondition will be true after the service has been completed.
- When making calls to a supplier, a software module should not violate the supplier's preconditions.
Performance implications
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 with assert. Asserts are by default compiled away in release mode in C/C++, and similarly deactivated in C# and Java.
Launching the Python interpreter with "-O" as an argument will likewise cause the Python code generator to not emit any bytecode for asserts.
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 into production by the compiler.
Relationship to software testing
Design by contract does not replace regular testing strategies, such as unit testing, integration testing and system 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 of test oracle, a way of testing the design by contract implementation.
Language support
Languages with native support
Languages that implement most DbC features natively include:- Ada 2012
- Ciao
- Clojure
- Cobra
- D
- Eiffel
- Fortress
- Kotlin
- Mercury
- Oxygene
- Racket
- Sather
- Scala
- SPARK
- Spec#
- Vala
- VDM
Languages with third-party support
- Ada, via GNAT pragmas for preconditions and postconditions.
- C and C++, via , the DBC for C preprocessor, GNU Nana, eCv and eCv++ formal verification tools, or the Digital Mars C++ compiler, via CTESK extension of C. Loki Library provides a mechanism named ContractChecker that verifies a class follows design by contract.
- C#, via Code Contracts
- Groovy via GContracts
- Go via
- Java:
- * Active:
- ** with AspectJ
- **
- ** Java Modeling Language
- ** Bean Validation
- **
- * Inactive/unknown:
- ** Jtest
- ** iContract2/JContracts
- ** Contract4J
- ** jContractor
- ** C4J
- ** Google CodePro Analytix
- ** SpringContracts for the Spring Framework
- **
- **
- ** JavaDbC using AspectJ
- ** JavaTESK using extension of Java
- ** chex4j using javassist
- ** highly customizable java-on-contracts
- JavaScript, via AspectJS, Cerny.js, ecmaDebug, jsContract, or jscategory.
- Common Lisp, via the macro facility or the CLOS metaobject protocol.
- Nemerle, via macros.
- Nim, via .
- Perl, via the CPAN modules Class::Contract or Carp::Datum.
- PHP, via , Praspel or Stuart Herbert's ContractLib.
- Python, using packages like icontract, PyContracts, Decontractors, dpcontracts, zope.interface, PyDBC or Contracts for Python. A permanent change to Python to support Design by Contracts was proposed in PEP-316, but deferred.
- Ruby, via Brian McCallister's DesignByContract, Ruby DBC ruby-contract or contracts.ruby.
- Rust via the library
- Tcl, via the XOTcl object-oriented extension.