Programming By Contract
   HOME

TheInfoList



OR:

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 Formal, formality, informal or informality imply the complying with, or not complying with, some set of requirements ( forms, in Ancient Greek). They may refer to: Dress code and events * Formal wear, attire for formal events * Semi-formal atti ...
, precise and verifiable interface specifications for
software components Component-based software engineering (CBSE), also called component-based development (CBD), is a style of software engineering that aims to construct a software system from components that are loosely-coupled and reusable. This emphasizes the sep ...
, which extend the ordinary definition of
abstract data type In computer science, an abstract data type (ADT) is a mathematical model for data types, defined by its behavior (semantics) from the point of view of a '' user'' of the data, specifically in terms of possible values, possible operations on data ...
s with
precondition In computer programming, a precondition is a condition or predicate that must always be true just prior to the execution of some section of code or before an operation in a formal specification. If a precondition is violated, the effect of the ...
s,
postcondition In computer programming, a postcondition is a condition or predicate that must always be true just after the execution of some section of code or after an operation in a formal specification. Postconditions are sometimes tested using assertions w ...
s and invariants. These specifications are referred to as "contracts", in accordance with a
conceptual metaphor In cognitive linguistics, conceptual metaphor, or cognitive metaphor, refers to the understanding of one idea, or conceptual domain, in terms of another. An example of this is the understanding of quantity in terms of directionality (e.g. "the pr ...
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 Distributed computing is a field of computer science that studies distributed systems, defined as computer systems whose inter-communicating components are located on different networked computers. The components of a distributed system commu ...
), the inverse approach is taken, meaning that the ''server component'' tests that all relevant preconditions hold true (before, or while, processing the ''client components request) and replies with a suitable error message if not.


History

The term was coined by
Bertrand Meyer Bertrand Meyer (; ; born 21 November 1950) is a French academic, author, and consultant in the field of computer languages. He created the Eiffel programming language and the concept of design by contract. Education and academic career 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 (1988, 1997) of his book ''
Object-Oriented Software Construction ''Object-Oriented Software Construction'', also called OOSC, is a book by Bertrand Meyer, widely considered a foundational text of object-oriented programming. The first edition was published in 1988; the second edition, extensively revised and e ...
''. 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 In the context of hardware and software systems, formal verification is the act of proving or disproving the correctness of a system with respect to a certain formal specification or property, using formal methods of mathematics. Formal ver ...
,
formal specification In computer science, formal specifications are mathematically based techniques whose purpose is to help with the implementation of systems and software. They are used to describe a system, to analyze its behavior, and to aid in its design by verify ...
and
Hoare logic Hoare logic (also known as Floyd–Hoare logic or Hoare rules) is a formal system with a set of logical rules for reasoning rigorously about the correctness of computer programs. It was proposed in 1969 by the British computer scientist and l ...
. The original contributions include: *A clear metaphor to guide the design process *The application to
inheritance Inheritance is the practice of receiving private property, titles, debts, entitlements, privileges, rights, and obligations upon the death of an individual. The rules of inheritance differ among societies and have changed over time. Offi ...
, in particular a formalism for redefinition and dynamic binding *The application to
exception handling In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
*The connection with automatic
software documentation Software documentation is written text or illustration that accompanies computer software or is embedded in the source code. The documentation either explains how the software operates or how to use it, and may mean different things to people in ...


Description

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 Method (, methodos, from μετά/meta "in pursuit or quest of" + ὁδός/hodos "a method, system; a way or manner" of doing, saying, etc.), literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In re ...
of a
class Class, Classes, or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used d ...
in
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
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 In computer programming, a precondition is a condition or predicate that must always be true just prior to the execution of some section of code or before an operation in a formal specification. If a precondition is violated, the effect of the ...
—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 In computer programming, a postcondition is a condition or predicate that must always be true just after the execution of some section of code or after an operation in a formal specification. Postconditions are sometimes tested using assertions w ...
—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 In computer programming, specifically object-oriented programming, a class invariant (or type invariant) is an invariant used for constraining objects of a class. Methods of the class should preserve the invariant. The class invariant constra ...
. The contract is semantically equivalent to a
Hoare triple Hoare logic (also known as Floyd–Hoare logic or Hoare rules) is a formal system with a set of logical rules for reasoning rigorously about the correctness of computer programs. It was proposed in 1969 by the British computer scientist and lo ...
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 language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s 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. Contracts can be written by code comments, enforced by a
test suite In software development, a test suite, less commonly known as a validation suite, is a collection of test cases that are intended to be used to test a software program to show that it has some specified set of behaviors. A test suite often conta ...
, 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: * 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 In medicine, a side effect is an effect of the use of a medicinal drug or other treatment, usually adverse but sometimes beneficial, that is unintended. Herbal and traditional medicines also have side effects. A drug or procedure usually used ...
*
Precondition In computer programming, a precondition is a condition or predicate that must always be true just prior to the execution of some section of code or before an operation in a formal specification. If a precondition is violated, the effect of the ...
s *
Postcondition In computer programming, a postcondition is a condition or predicate that must always be true just after the execution of some section of code or after an operation in a formal specification. Postconditions are sometimes tested using assertions w ...
s * 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 In computer programming, specifically object-oriented programming, a class invariant (or type invariant) is an invariant used for constraining objects of a class. Methods of the class should preserve the invariant. The class invariant constra ...
. 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 Software documentation is written text or illustration that accompanies computer software or is embedded in the source code. The documentation either explains how the software operates or how to use it, and may mean different things to people in ...
for the behavior of that module.


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 Assertion or assert may refer to: Computing * Assertion (software development), a computer programming technique * assert.h, a header file in the standard library of the C programming language * Assertion definition language, a specification lan ...
. 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" (for "optimize") 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 in production by the compiler.


Relationship to software testing

Design by contract does not replace regular testing strategies, such as
unit testing Unit testing, component or module testing, is a form of software testing by which isolated source code is tested to validate expected behavior. Unit testing describes tests that are run at the unit-level to contrast testing at the Integration ...
,
integration testing Integration testing is a form of software testing in which multiple software components, modules, or services are tested together to verify they work as expected when combined. The focus is on testing the interactions and data exchange between i ...
and
system testing System testing, a.k.a. end-to-end (E2E) testing, is testing conducted on a complete software system. System testing describes testing at the system level to contrast to testing at the system integration, integration or unit level. System t ...
. 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 In software testing, a test oracle (or just oracle) is a provider of information that describes correct output based on the input of a test case. Testing with an oracle involves comparing actual results of the system under test (SUT) with the ex ...
, 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 ( , ) is an informal salutation in the Italian language that is used for both " hello" and "goodbye". Originally from the Venetian language, it has entered the vocabulary of English and of many other languages around the world. Its dual mea ...
*
Clojure Clojure (, like ''closure'') is a dynamic programming language, dynamic and functional programming, functional dialect (computing), dialect of the programming language Lisp (programming language), Lisp on the Java (software platform), Java platfo ...
*
Cobra COBRA or Cobra, often stylized as CoBrA, was a European avant-garde art group active from 1948 to 1951. The name was coined in 1948 by Christian Dotremont from the initials of the members' home countries' capital cities: Copenhagen (Co), Brussels ...
* C++ (since
C++26 C26 or C-26 may refer to: * C.26, a British World War I Coastal class airship * C26 road (Namibia) * Caldwell 26, a spiral galaxy * Caspar C 26, German sport plane * Douglas C-26 Dolphin, an American military flying boat * Fairchild C-26 Metro ...
) * D * Dafny * Eiffel *
Fortress A fortification (also called a fort, fortress, fastness, or stronghold) is a military construction designed for the defense of territories in warfare, and is used to establish rule in a region during peacetime. The term is derived from L ...
* Kotlin * Mercury * Oxygene (formerly Chrome and Delphi Prism) * Racket (including higher order contracts, and emphasizing that contract violations must blame the guilty party and must do so with an accurate explanation) *
Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH) ...
(experimental) * Sather * Scala
Strong typing In computer programming, one of the many ways that programming languages are colloquially classified is whether the language's type system makes it strongly typed or weakly typed (loosely typed). However, there is no precise technical definition o ...
as another "contract enforcing" in Scala, see discussion a
scala-lang.org/
* SPARK (via
static analysis Static analysis, static projection, or static scoring is a simplified analysis wherein the effect of an immediate change to a system is calculated without regard to the longer-term response of the system to that change. If the short-term effect i ...
of Ada programs) * Vala * Vienna Development Method (VDM) Additionally, the standard method combination in the
Common Lisp Object System The Common Lisp Object System (CLOS) is the facility for object-oriented programming in American National Standards Institute, ANSI Common Lisp. CLOS is a powerful dynamic programming language, dynamic object system which differs radically from t ...
has the method qualifiers :before, :after and :around that allow writing contracts as auxiliary methods, among other uses.


See also

*
Component-based software engineering Component-based software engineering (CBSE), also called component-based development (CBD), is a style of software engineering that aims to construct a software system from software component, components that are loosely-Coupling (computer program ...
*
Correctness (computer science) In theoretical computer science, an algorithm is correct with respect to a program specification, specification if it behaves as specified. Best explored is ''functional'' correctness, which refers to the input–output behavior of the algorithm: ...
* Defensive programming * Fail-fast system *
Formal methods In computer science, formal methods are mathematics, mathematically rigorous techniques for the formal specification, specification, development, Program analysis, analysis, and formal verification, verification of software and computer hardware, ...
*
Hoare logic Hoare logic (also known as Floyd–Hoare logic or Hoare rules) is a formal system with a set of logical rules for reasoning rigorously about the correctness of computer programs. It was proposed in 1969 by the British computer scientist and l ...
*
Modular programming Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect or "concern" of the d ...
*
Program derivation In computer science, program derivation is the derivation of a program from its specification, by mathematical means. To ''derive'' a program means to write a formal specification, which is usually non-executable, and then apply mathematically corr ...
*
Program refinement Refinement is a generic term of computer science that encompasses various approaches for producing correct computer programs and simplifying existing programs to enable their formal verification. Program refinement In formal methods, program re ...
*
Strong typing In computer programming, one of the many ways that programming languages are colloquially classified is whether the language's type system makes it strongly typed or weakly typed (loosely typed). However, there is no precise technical definition o ...
*
Test-driven development Test-driven development (TDD) is a way of writing source code, code that involves writing an test automation, automated unit testing, unit-level test case that fails, then writing just enough code to make the test pass, then refactoring both the ...
*
Typestate analysis Typestate analysis, sometimes called protocol analysis, is a form of program analysis employed in programming languages. It is most commonly applied to object-oriented languages. Typestates define valid sequences of operations that can be performe ...


Notes


Bibliography

* 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


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. *
Using Code Contracts for Safer Code
{{DEFAULTSORT:Design By Contract Software design Programming paradigms