Design by contract: Difference between revisions
→Languages with third-party support: update Rust third-party support. libhoare is a very much out of date compiler plugin (which are no longer supported?), the contracts crate works on the stable Rust channel and uses procedural macros instead |
Citation bot (talk | contribs) Added date. | Use this bot. Report bugs. | Suggested by Neko-chan | #UCB_webform 43/500 |
||
(37 intermediate revisions by 30 users not shown) | |||
Line 1: | Line 1: | ||
{{Short description|Approach for designing software}} |
|||
[[File:Design by contract.svg|thumbnail|A design by contract scheme]] |
[[File:Design by contract.svg|thumbnail|A design by contract scheme]] |
||
'''Design by contract''' ('''DbC'''), also known as '''contract programming''', '''programming by contract''' and '''design-by-contract programming''', is an approach for [[software design|designing software]]. |
'''Design by contract''' ('''DbC'''), also known as '''contract programming''', '''programming by contract''' and '''design-by-contract programming''', is an approach for [[software design|designing software]]. |
||
Line 6: | Line 7: | ||
The DbC approach [[Offensive_programming|assumes]] all ''client components'' that invoke an operation on a ''server component'' will meet the preconditions specified as required for that operation. |
The DbC approach [[Offensive_programming|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 (as in multi-channel or [[distributed computing]]) the [[defensive_programming|inverse approach]] is taken, meaning that the ''server component'' tests that all relevant preconditions hold true (before, or while, processing the ''client component'''s request) and replies with a suitable error message if not. |
Where this assumption is considered too risky (as in multi-channel or [[distributed computing]]), the [[defensive_programming|inverse approach]] is taken, meaning that the ''server component'' tests that all relevant preconditions hold true (before, or while, processing the ''client component'''s request) and replies with a suitable error message if not. |
||
==History== |
==History== |
||
The term was coined by [[Bertrand Meyer]] in connection with his design of the [[Eiffel (programming language)|Eiffel programming language]] and first described in various articles starting in 1986<ref>Meyer, Bertrand: ''Design by Contract'', Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986</ref><ref>Meyer, Bertrand: ''Design by Contract'', in ''Advances in Object-Oriented Software Engineering'', eds. D. Mandrioli and B. Meyer, Prentice Hall, 1991, pp. 1–50</ref><ref>Meyer, Bertrand: |
The term was coined by [[Bertrand Meyer]] in connection with his design of the [[Eiffel (programming language)|Eiffel programming language]] and first described in various articles starting in 1986<ref>Meyer, Bertrand: ''Design by Contract'', Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986</ref><ref>Meyer, Bertrand: ''Design by Contract'', in ''Advances in Object-Oriented Software Engineering'', eds. D. Mandrioli and B. Meyer, Prentice Hall, 1991, pp. 1–50</ref><ref>Meyer, Bertrand: "[http://se.ethz.ch/~meyer/publications/computer/contract.pdf Applying "Design by Contract"]", in ''Computer'' (IEEE), 25, 10, October 1992, pp. 40–51.</ref> and the two successive editions (1988, 1997) 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.<ref name=DbC_tm_words>{{cite web|url=http://tess2.uspto.gov/bin/showfield?f=doc&state=4010:lsqmmo.2.2|title=United States Patent and Trademark Office registration for "DESIGN BY CONTRACT"|access-date=2009-06-22|archive-date=2016-12-21|archive-url=https://web.archive.org/web/20161221062729/http://tess2.uspto.gov/bin/showfield?f=doc&state=4010:lsqmmo.2.2|url-status=dead}}{{dead link|date=February 2024}}</ref><ref name=DbC_tm_design>{{cite web|url=http://tess2.uspto.gov/bin/showfield?f=doc&state=4010:lsqmmo.2.1|title=United States Patent and Trademark Office registration for the graphic design with words "Design by Contract"|access-date=2009-06-22|archive-date=2016-12-21|archive-url=https://web.archive.org/web/20161221062436/http://tess2.uspto.gov/bin/showfield?f=doc&state=4010:lsqmmo.2.1|url-status=dead}}{{dead link|date=February 2024}}</ref> The current owner of this trademark is Eiffel Software.<ref name=DbC_tm_words2>{{cite web|url=http://tarr.uspto.gov/servlet/tarr?regser=serial&entry=78342277|title=Trademark Status & Document Retrieval - 78342277 |website=USPTO Trademark Application and Registration Retrieval}}</ref><ref name=DbC_tm_design2>{{cite web|url=http://tarr.uspto.gov/servlet/tarr?regser=serial&entry=78342308|title=Trademark Status & Document Retrieval - 78342308 |website=USPTO Trademark Application and Registration Retrieval}}</ref> |
||
Design by contract has its roots in work on [[formal verification]], [[formal specification]] and [[Hoare logic]]. The original contributions include: |
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 |
*A clear metaphor to guide the design process |
||
*The application to [[inheritance ( |
*The application to [[inheritance (object-oriented programming)|inheritance]], in particular a formalism for redefinition and [[dynamic binding (computer science)|dynamic binding]] |
||
*The application to [[exception (computer science)|exception handling]] |
*The application to [[exception (computer science)|exception handling]] |
||
*The connection with automatic [[software documentation]] |
*The connection with automatic [[software documentation]] |
||
Line 68: | Line 69: | ||
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. |
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 [[Assertion (software development)|assert]]. Asserts are by default compiled away in release mode in C/C++, and similarly deactivated in C#<ref>{{cite web|url=https://msdn.microsoft.com/en-us/library/ttcc4x86.aspx|title=Assertions in Managed Code|website=msdn.microsoft.com}}</ref> and Java. |
In many programming languages, contracts are implemented with [[Assertion (software development)|assert]]. Asserts are by default compiled away in release mode in C/C++, and similarly deactivated in C#<ref>{{cite web|url=https://msdn.microsoft.com/en-us/library/ttcc4x86.aspx|title=Assertions in Managed Code|website=Microsoft Developer Network |date=15 November 2016 |url-status=live |archive-url= https://web.archive.org/web/20180822105637/https://msdn.microsoft.com/en-us/library/ttcc4x86.aspx |archive-date= Aug 22, 2018 }}</ref> 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.<ref>[https://docs.python.org/3/reference/simple_stmts.html#grammar-token-assert-stmt Official Python Docs, ''assert statement'']</ref> |
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.<ref>[https://docs.python.org/3/reference/simple_stmts.html#grammar-token-assert-stmt Official Python Docs, ''assert statement'']</ref> |
||
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 |
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. |
||
==Relationship to software testing== |
==Relationship to software testing== |
||
Line 93: | Line 94: | ||
| last = Bright |
| last = Bright |
||
| first = Walter |
| first = Walter |
||
| authorlink = |
|||
| title = D Programming Language, Contract Programming |
| title = D Programming Language, Contract Programming |
||
| website = |
|||
| publisher = Digital Mars |
| publisher = Digital Mars |
||
| date = 2014-11-01 |
| date = 2014-11-01 |
||
| url = http://dlang.org/contracts.html |
| url = http://dlang.org/contracts.html |
||
| |
| access-date = 2014-11-10 |
||
}} |
}} |
||
</ref> |
</ref> |
||
Line 107: | Line 106: | ||
* [[Kotlin_(programming_language)|Kotlin]] |
* [[Kotlin_(programming_language)|Kotlin]] |
||
* [[Mercury (programming language)|Mercury]] |
* [[Mercury (programming language)|Mercury]] |
||
* [[Oxygene (programming language)|Oxygene]] (formerly Chrome and Delphi Prism<ref>{{cite web | url=http://edn.embarcadero.com/article/39398 | title=Write Cleaner, Higher Quality Code with Class Contracts in Delphi Prism | publisher=Embarcadero Technologies | |
* [[Oxygene (programming language)|Oxygene]] (formerly Chrome and Delphi Prism<ref>{{cite web | url=http://edn.embarcadero.com/article/39398 | title=Write Cleaner, Higher Quality Code with Class Contracts in Delphi Prism | publisher=Embarcadero Technologies | access-date=20 January 2016 | author=Hodges, Nick | archive-date=26 April 2021 | archive-url=https://web.archive.org/web/20210426163433/https://edn.embarcadero.com/article/39398 | url-status=dead }}</ref>) |
||
* [[Racket (programming language)|Racket]] (including higher order contracts, and emphasizing that contract violations must blame the guilty party and must do so with an accurate explanation<ref>Findler, Felleisen [http://www.eecs.northwestern.edu/~robby/pubs/papers/ho-contracts-icfp2002.pdf Contracts for Higher-Order Functions]</ref>) |
* [[Racket (programming language)|Racket]] (including higher order contracts, and emphasizing that contract violations must blame the guilty party and must do so with an accurate explanation<ref>Findler, Felleisen [http://www.eecs.northwestern.edu/~robby/pubs/papers/ho-contracts-icfp2002.pdf Contracts for Higher-Order Functions]</ref>) |
||
* [[Sather]] |
* [[Sather]] |
||
* [[Scala_(programming_language)|Scala]]<ref name="scala-assertions-dbc"> |
* [[Scala_(programming_language)|Scala]]<ref name="scala-assertions-dbc"> |
||
{{cite web |
{{cite web |
||
| last = |
|||
| first = |
|||
| authorlink = |
|||
| title = Scala Standard Library Docs - Assertions |
| title = Scala Standard Library Docs - Assertions |
||
| website = |
|||
| publisher = EPFL |
| publisher = EPFL |
||
| date = |
|||
| url = https://www.scala-lang.org/api/current/scala/Predef$.html |
| url = https://www.scala-lang.org/api/current/scala/Predef$.html |
||
| |
| access-date = 2019-05-24 |
||
}} |
}} |
||
</ref><ref>[[Strong typing]] as another "contract enforcing" in Scala, see discussion at [https://www.scala-lang.org/old/node/6958 scala-lang.org/].</ref> |
</ref><ref>[[Strong typing]] as another "contract enforcing" in Scala, see discussion at [https://www.scala-lang.org/old/node/6958 scala-lang.org/].</ref> |
||
* [[SPARK (programming language)|SPARK]] (via [[static code analysis|static analysis]] of [[Ada (programming language)|Ada]] programs) |
* [[SPARK (programming language)|SPARK]] (via [[static code analysis|static analysis]] of [[Ada (programming language)|Ada]] programs) |
||
* [[Spec sharp|Spec#]] |
|||
* [[Vala (programming language)|Vala]] |
* [[Vala (programming language)|Vala]] |
||
* [[VDM specification language|VDM]] |
* [[VDM specification language|VDM]] |
||
Additionally, the standard method combination in the [[Common Lisp Object System]] has the method qualifiers <code>:before</code>, <code>:after</code> and <code>:around</code> that allow writing contracts as auxiliary methods, among other uses. |
|||
===Languages with third-party support=== |
===Languages with third-party support=== |
||
{{multiple issues|section=yes| |
|||
{{External links|section|date=January 2022}} |
|||
{{cleanup list|section|date=January 2022}} |
|||
}} |
|||
Various libraries, preprocessors and other tools have been developed for existing programming languages without native design by contract support: |
Various libraries, preprocessors and other tools have been developed for existing programming languages without native design by contract support: |
||
* [[Ada (programming language)|Ada]], via [[GNAT]] pragmas for preconditions and postconditions. |
* [[Ada (programming language)|Ada]], via [[GNAT]] pragmas for preconditions and postconditions. |
||
* [[C (programming language)|C]] |
|||
* [[C (programming language)|C]] and [[C++]], via [https://www.boost.org/doc/libs/master/libs/contract/doc/html/index.html Boost.Contract], 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 (C++)|Loki Library]] provides a mechanism named ContractChecker that verifies a class follows design by contract. |
|||
** ''DBC for C'' [[preprocessor]] |
|||
⚫ | * [[C Sharp (programming language)|C#]] (and other .NET languages), via ''Code Contracts''<ref>{{cite web|url=https://docs.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts|title=Code Contracts|website= |
||
** ''[[GNU Nana]]'' |
|||
** ''eCv'' [[formal verification]] tools |
|||
* [[C++]]: |
|||
** [https://www.boost.org/doc/libs/master/libs/contract/doc/html/index.html Boost.Contract] |
|||
** ''eCv++'' [[formal verification]] tools |
|||
** [[Digital Mars]] C++ compiler via [[CTESK]] extension of C |
|||
** [[Loki (C++)|Loki Library]] provides a mechanism named ContractChecker that verifies a class follows design by contract. |
|||
** [https://github.com/Bambofy/dbc_cpp DBC C++] Design by contract for C++ |
|||
⚫ | * [[C Sharp (programming language)|C#]] (and other .NET languages), via ''Code Contracts''<ref>{{cite web|url=https://docs.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts|title=Code Contracts|website=Microsoft Developer Network |url-status=live |archive-url=https://web.archive.org/web/20181115031934/https://docs.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts |archive-date= Nov 15, 2018 }}</ref> (a [[Microsoft Research]] project integrated into the [[.NET Framework]] 4.0) |
||
* [[Groovy (programming language)|Groovy]] via GContracts |
* [[Groovy (programming language)|Groovy]] via GContracts |
||
*[[Go (programming language)|Go]] via [https://github.com/drblez/dbc dbc] |
*[[Go (programming language)|Go]] via [https://github.com/drblez/dbc dbc] or [https://github.com/Parquery/gocontracts gocontracts] |
||
* [[Java (programming language)|Java]]: |
* [[Java (programming language)|Java]]: |
||
** Active: |
** Active: |
||
Line 142: | Line 150: | ||
*** [[Bean Validation]] (only pre- and postconditions)<ref>{{cite web|url=http://beanvalidation.org/1.1/spec/|title=Bean Validation specification|website=beanvalidation.org}}</ref> |
*** [[Bean Validation]] (only pre- and postconditions)<ref>{{cite web|url=http://beanvalidation.org/1.1/spec/|title=Bean Validation specification|website=beanvalidation.org}}</ref> |
||
*** [http://www.valid4j.org valid4j] |
*** [http://www.valid4j.org valid4j] |
||
*** [https://swdes.net/en/content/safer-project SafeR] (with safe references) |
|||
** Inactive/unknown: |
** Inactive/unknown: |
||
*** [[Jtest]] (active but DbC seems not to be supported anymore)<ref>https://www.parasoft.com/wp-content/uploads/pdf/JtestDataSheet.pdf</ref> |
*** [[Jtest]] (active but DbC seems not to be supported anymore)<ref>{{Cite web|url=https://www.parasoft.com/wp-content/uploads/pdf/JtestDataSheet.pdf |archive-url=https://ghostarchive.org/archive/20221009/https://www.parasoft.com/wp-content/uploads/pdf/JtestDataSheet.pdf |archive-date=2022-10-09 |url-status=live|title=Software Testing Help from the Experts | Parasoft Resources}}</ref> |
||
*** iContract2/JContracts |
*** iContract2/JContracts |
||
*** Contract4J |
*** Contract4J |
||
Line 150: | Line 159: | ||
*** Google CodePro Analytix |
*** Google CodePro Analytix |
||
*** SpringContracts for the [[Spring Framework]] |
*** SpringContracts for the [[Spring Framework]] |
||
*** [http://csd.informatik.uni-oldenburg.de/~jass/ Jass] |
*** [http://csd.informatik.uni-oldenburg.de/~jass/ Jass] {{Webarchive|url=https://web.archive.org/web/20030403224637/http://csd.informatik.uni-oldenburg.de/~jass/ |date=2003-04-03 }} |
||
*** [http://modernjass.sourceforge.net Modern Jass] (successor is Cofoja)<ref>{{cite web |url=https://cofoja.googlecode.com/files/cofoja-20110112.pdf |title=Archived copy | |
*** [http://modernjass.sourceforge.net Modern Jass] (successor is Cofoja)<ref>{{cite web |url=https://cofoja.googlecode.com/files/cofoja-20110112.pdf |title=Archived copy |access-date=2016-03-25 |url-status=dead |archive-url=https://web.archive.org/web/20160328164727/http://cofoja.googlecode.com/files/cofoja-20110112.pdf |archive-date=2016-03-28 }} p. 2</ref><ref>{{cite web|url=https://github.com/nhatminhle/cofoja/issues/5|title=No chance of releasing under Apache/Eclipse/MIT/BSD license? · Issue #5 · nhatminhle/cofoja|website=GitHub}}</ref> |
||
*** JavaDbC using AspectJ |
*** JavaDbC using AspectJ |
||
*** [[JavaTESK]] using extension of Java |
*** [[JavaTESK]] using extension of Java |
||
*** chex4j using javassist |
*** chex4j using javassist |
||
*** highly customizable java-on-contracts |
*** highly customizable java-on-contracts |
||
* [[JavaScript]], via AspectJS (specifically, AJS_Validator), Cerny.js, ecmaDebug, jsContract, [https://www.npmjs.com/package/dbc-code-contracts dbc-code-contracts] or jscategory. |
* [[JavaScript]], via [https://github.com/final-hill/decorator-contracts decorator-contracts], AspectJS (specifically, AJS_Validator), Cerny.js, ecmaDebug, jsContract, [https://www.npmjs.com/package/dbc-code-contracts dbc-code-contracts] or jscategory. |
||
* [[Common Lisp]], via the macro facility or the [[Common Lisp Object System|CLOS]] [[metaobject|metaobject protocol]]. |
* [[Common Lisp]], via the macro facility or the [[Common Lisp Object System|CLOS]] [[metaobject|metaobject protocol]]. |
||
* [[Nemerle]], via macros. |
* [[Nemerle]], via macros. |
||
Line 162: | Line 171: | ||
* [[Perl]], via the [[CPAN]] modules Class::Contract (by [[Damian Conway]]) or Carp::Datum (by Raphael Manfredi). |
* [[Perl]], via the [[CPAN]] modules Class::Contract (by [[Damian Conway]]) or Carp::Datum (by Raphael Manfredi). |
||
* [[PHP]], via [https://github.com/php-deal/framework PhpDeal], [[Praspel]] or Stuart Herbert's ContractLib. |
* [[PHP]], via [https://github.com/php-deal/framework PhpDeal], [[Praspel]] or Stuart Herbert's ContractLib. |
||
* [[Python (programming language)|Python]], using packages like icontract, PyContracts, |
* [[Python (programming language)|Python]], using packages like [https://github.com/life4/deal deal], [https://pypi.org/project/icontract/ icontract], [https://pypi.org/project/PyContracts/ PyContracts], [https://pypi.org/project/dpcontracts/ dpcontracts], or [https://pypi.org/project/zope.interface/ zope.interface]. A permanent change to Python to support design by contracts was proposed in [https://peps.python.org/pep-0316/ PEP-316] in 2003, but is deferred. |
||
* [[Ruby (programming language)|Ruby]], via Brian McCallister's DesignByContract, Ruby DBC ruby-contract or contracts.ruby. |
* [[Ruby (programming language)|Ruby]], via Brian McCallister's DesignByContract, Ruby DBC ruby-contract or contracts.ruby. |
||
* [[Rust (programming language)|Rust]] via the [https://crates.io/crates/contracts contracts] crate. |
* [[Rust (programming language)|Rust]] via the [https://crates.io/crates/contracts contracts] crate. |
||
* [[Swift (programming language)|Swift]] via the [https://github.com/busybusy/DBC-Apple cocoapod by Jim Boyd]. |
|||
* [[Tcl]], via the [[XOTcl]] object-oriented extension. |
* [[Tcl]], via the [[XOTcl]] object-oriented extension. |
||
Line 171: | Line 181: | ||
* [[Correctness (computer science)]] |
* [[Correctness (computer science)]] |
||
* [[Defensive programming]] |
* [[Defensive programming]] |
||
* [[Fail-fast]] |
* [[Fail-fast system]] |
||
* [[Formal methods]] |
* [[Formal methods]] |
||
* [[Hoare logic]] |
* [[Hoare logic]] |
||
Line 195: | Line 205: | ||
* [http://archive.eiffel.com/doc/manuals/technology/contract/ Building bug-free O-O software: An introduction to Design by Contract(TM)] Older material on DbC. |
* [http://archive.eiffel.com/doc/manuals/technology/contract/ Building bug-free O-O software: An introduction to Design by Contract(TM)] Older material on DbC. |
||
* [http://www.rps-obix.com/docs/manuals/design_by_contract_contract_programming.html Benefits and drawbacks; implementation in RPS-Obix] |
* [http://www.rps-obix.com/docs/manuals/design_by_contract_contract_programming.html Benefits and drawbacks; implementation in RPS-Obix] |
||
* Bertrand Meyer, [http://se.ethz.ch/~meyer/publications/computer/contract.pdf ''Applying "Design by Contract"''], IEEE Computer, October 1992. |
|||
* [http://buksbaum.us/2011/04/20/using-code-contracts-for-safer-code/ Using Code Contracts for Safer Code] |
* [http://buksbaum.us/2011/04/20/using-code-contracts-for-safer-code/ Using Code Contracts for Safer Code] |
||
{{Design}} |
{{Design}} |
||
Latest revision as of 16:09, 6 May 2024
Design by contract (DbC), 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 (as in multi-channel or distributed computing), the inverse approach is taken, meaning that the server component tests that all relevant preconditions hold true (before, or while, processing the client component's request) and replies with a suitable error message if not.
History
[edit]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[1][2][3] and the two successive editions (1988, 1997) 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.[4][5] The current owner of this trademark is Eiffel Software.[6][7]
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
[edit]The central idea of DbC is a metaphor on how elements of a software system collaborate with each other on the basis of mutual obligations and benefits. The metaphor comes from business life, where a "client" and a "supplier" agree on a "contract" that defines, for example, that:
- The supplier must provide a certain product (obligation) and is entitled to expect that the client has paid its fee (benefit).
- The client must pay the fee (obligation) and is entitled to get the product (benefit).
- Both parties must satisfy certain obligations, such as laws and regulations, applying to all contracts.
Similarly, if the method of a class in object-oriented programming provides a certain functionality, it may:
- 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 (the method itself), 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 (the main benefit of calling the method) for the client.
- Maintain a certain property, assumed on entry and guaranteed on exit: the class invariant.
The contract is semantically equivalent to a Hoare triple which formalises the obligations. This can be summarised by the "three questions" that the designer must repeatedly answer in the contract:
- What does the contract expect?
- What does the contract guarantee?
- What does the contract maintain?
Many programming languages have facilities to make assertions like these. However, DbC considers these contracts to be so crucial to software correctness that they should be part of the design process. In effect, DbC advocates writing the assertions first.[citation needed] Contracts can be written by code comments, enforced by a test 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]
- 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
- (more rarely) Performance guarantees, e.g. for time or space used
Subclasses in an inheritance hierarchy are allowed to weaken preconditions (but not strengthen them) and strengthen postconditions and invariants (but not weaken them). These rules approximate behavioural 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 of class 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 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.
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 of software documentation for the behavior of that module.
Performance implications
[edit]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#[8] 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.[9]
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.
Relationship to software testing
[edit]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
[edit]Languages with native support
[edit]Languages that implement most DbC features natively include:
- Ada 2012
- Ciao
- Clojure
- Cobra
- D[10]
- Dafny
- Eiffel
- Fortress
- Kotlin
- Mercury
- Oxygene (formerly Chrome and Delphi Prism[11])
- Racket (including higher order contracts, and emphasizing that contract violations must blame the guilty party and must do so with an accurate explanation[12])
- Sather
- Scala[13][14]
- SPARK (via static analysis of Ada programs)
- Vala
- VDM
Additionally, the standard method combination in the Common Lisp Object System has the method qualifiers :before
, :after
and :around
that allow writing contracts as auxiliary methods, among other uses.
Languages with third-party support
[edit]This section has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these messages)
|
Various libraries, preprocessors and other tools have been developed for existing programming languages without native design by contract support:
- Ada, via GNAT pragmas for preconditions and postconditions.
- C
- DBC for C preprocessor
- GNU Nana
- eCv formal verification tools
- C++:
- Boost.Contract
- eCv++ formal verification tools
- Digital Mars C++ compiler via CTESK extension of C
- Loki Library provides a mechanism named ContractChecker that verifies a class follows design by contract.
- DBC C++ Design by contract for C++
- C# (and other .NET languages), via Code Contracts[15] (a Microsoft Research project integrated into the .NET Framework 4.0)
- Groovy via GContracts
- Go via dbc or gocontracts
- Java:
- Active:
- OVal with AspectJ
- Contracts for Java (Cofoja)
- Java Modeling Language (JML)
- Bean Validation (only pre- and postconditions)[16]
- valid4j
- SafeR (with safe references)
- Inactive/unknown:
- Jtest (active but DbC seems not to be supported anymore)[17]
- iContract2/JContracts
- Contract4J
- jContractor
- C4J
- Google CodePro Analytix
- SpringContracts for the Spring Framework
- Jass Archived 2003-04-03 at the Wayback Machine
- Modern Jass (successor is Cofoja)[18][19]
- JavaDbC using AspectJ
- JavaTESK using extension of Java
- chex4j using javassist
- highly customizable java-on-contracts
- Active:
- JavaScript, via decorator-contracts, AspectJS (specifically, AJS_Validator), Cerny.js, ecmaDebug, jsContract, dbc-code-contracts or jscategory.
- Common Lisp, via the macro facility or the CLOS metaobject protocol.
- Nemerle, via macros.
- Nim, via macros.
- Perl, via the CPAN modules Class::Contract (by Damian Conway) or Carp::Datum (by Raphael Manfredi).
- PHP, via PhpDeal, Praspel or Stuart Herbert's ContractLib.
- Python, using packages like deal, icontract, PyContracts, dpcontracts, or zope.interface. A permanent change to Python to support design by contracts was proposed in PEP-316 in 2003, but is deferred.
- Ruby, via Brian McCallister's DesignByContract, Ruby DBC ruby-contract or contracts.ruby.
- Rust via the contracts crate.
- Swift via the cocoapod by Jim Boyd.
- Tcl, via the XOTcl object-oriented extension.
See also
[edit]- Component-based software engineering
- Correctness (computer science)
- Defensive programming
- Fail-fast system
- Formal methods
- Hoare logic
- Modular programming
- Program derivation
- Program refinement
- Strong typing
- Test-driven development
- Typestate analysis
Notes
[edit]- ^ Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986
- ^ Meyer, Bertrand: Design by Contract, in Advances in Object-Oriented Software Engineering, eds. D. Mandrioli and B. Meyer, Prentice Hall, 1991, pp. 1–50
- ^ Meyer, Bertrand: "Applying "Design by Contract"", in Computer (IEEE), 25, 10, October 1992, pp. 40–51.
- ^ "United States Patent and Trademark Office registration for "DESIGN BY CONTRACT"". Archived from the original on 2016-12-21. Retrieved 2009-06-22.[dead link]
- ^ "United States Patent and Trademark Office registration for the graphic design with words "Design by Contract"". Archived from the original on 2016-12-21. Retrieved 2009-06-22.[dead link]
- ^ "Trademark Status & Document Retrieval - 78342277". USPTO Trademark Application and Registration Retrieval.
- ^ "Trademark Status & Document Retrieval - 78342308". USPTO Trademark Application and Registration Retrieval.
- ^ "Assertions in Managed Code". Microsoft Developer Network. 15 November 2016. Archived from the original on Aug 22, 2018.
- ^ Official Python Docs, assert statement
- ^ Bright, Walter (2014-11-01). "D Programming Language, Contract Programming". Digital Mars. Retrieved 2014-11-10.
- ^ Hodges, Nick. "Write Cleaner, Higher Quality Code with Class Contracts in Delphi Prism". Embarcadero Technologies. Archived from the original on 26 April 2021. Retrieved 20 January 2016.
- ^ Findler, Felleisen Contracts for Higher-Order Functions
- ^ "Scala Standard Library Docs - Assertions". EPFL. Retrieved 2019-05-24.
- ^ Strong typing as another "contract enforcing" in Scala, see discussion at scala-lang.org/.
- ^ "Code Contracts". Microsoft Developer Network. Archived from the original on Nov 15, 2018.
- ^ "Bean Validation specification". beanvalidation.org.
- ^ "Software Testing Help from the Experts | Parasoft Resources" (PDF). Archived (PDF) from the original on 2022-10-09.
- ^ "Archived copy" (PDF). Archived from the original (PDF) on 2016-03-28. Retrieved 2016-03-25.
{{cite web}}
: CS1 maint: archived copy as title (link) p. 2 - ^ "No chance of releasing under Apache/Eclipse/MIT/BSD license? · Issue #5 · nhatminhle/cofoja". GitHub.
Bibliography
[edit]- Mitchell, Richard, and McKim, Jim: Design by Contract: by example, Addison-Wesley, 2002
- A wikibook describing DBC closely to the original model.
- McNeile, Ashley: A framework for the semantics of behavioral contracts. Proceedings of the Second International Workshop on Behaviour Modelling: Foundation and Applications (BM-FA '10). ACM, New York, NY, USA, 2010. This paper discusses generalized notions of Contract and Substitutability.
External links
[edit]- The Power of Design by Contract(TM) A top-level description of DbC, with links to additional resources.
- Building bug-free O-O software: An introduction to Design by Contract(TM) Older material on DbC.
- Benefits and drawbacks; implementation in RPS-Obix
- Using Code Contracts for Safer Code