Design by contract

This article needs additional citations for verification. Please help improve this article by adding 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)

|

Approach for designing software

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 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.

Design by contract may look something like this:[8]

int f(const int x)
pre(x != 1) // a precondition assertion
post(r : r == x && r != 2) // a postcondition assertion; r names the result object of f

contract_assert(x != 3); // an assertion statement
return x;

## 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#[9] 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.[10]

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
* C++ (since C++26)
* D[11]
* Dafny
* Eiffel
* Fortress
* Kotlin
* Mercury
* Oxygene (formerly Chrome and Delphi Prism[12])
* Racket (including higher order contracts, and emphasizing that contract violations must blame the guilty party and must do so with an accurate explanation[13])
* Sather
* Scala[14][15]
* SPARK (via static analysis of Ada programs)
* Vala
* Vienna Development Method (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.

## 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]

1. ^ Meyer, Bertrand: Design by Contract, Technical Report TR-EI-12/CO, Interactive Software Engineering Inc., 1986
2. ^ Meyer, Bertrand: Design by Contract, in Advances in Object-Oriented Software Engineering, eds. D. Mandrioli and B. Meyer, Prentice Hall, 1991, pp. 1–50
3. ^ Meyer, Bertrand: "Applying "Design by Contract"", in Computer (IEEE), 25, 10, October 1992, pp. 40–51.
4. ^ "United States Patent and Trademark Office registration for "DESIGN BY CONTRACT"". Archived from the original on 2016-12-21. Retrieved 2009-06-22.
5. ^ "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.
6. ^ "Trademark Status & Document Retrieval - 78342277". USPTO Trademark Application and Registration Retrieval.
7. ^ "Trademark Status & Document Retrieval - 78342308". USPTO Trademark Application and Registration Retrieval.
8. ^ "Contracts for C++" (PDF). 13 February 2025.
9. ^ "Assertions in Managed Code". Microsoft Developer Network. 15 November 2016. Archived from the original on Aug 22, 2018.
10. ^ Official Python Docs, assert statement
11. ^ Bright, Walter (2014-11-01). "D Programming Language, Contract Programming". Digital Mars. Retrieved 2014-11-10.
12. ^ 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.
13. ^ Findler, Felleisen Contracts for Higher-Order Functions
14. ^ "Scala Standard Library Docs - Assertions". EPFL. Retrieved 2019-05-24.
15. ^ Strong typing as another "contract enforcing" in Scala, see discussion at scala-lang.org/.

## 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[usurped]
* Using Code Contracts for Safer Code

* v
* t
* e

Design

* Outline
* Designer

Disciplines

| Communication
design|

* Advertising
* Book design
* Brand design
* Exhibit design
* Film title design
* Graphic design
* Motion
* Postage stamp design
* Print design
* Illustration
* Information design
* Instructional design
* News design
* Photography
* Retail design
* Signage / Traffic sign design
* Typography / Type design
* Video design
* Visual merchandising

|

Environmental
design|

* Architecture
* Architectural lighting design
* Building design
* Passive solar
* Ecological design
* Environmental impact design
* Garden design
* Computer-aided
* Healthy community design
* Hotel design
* Interior architecture
* Interior design
* EID
* Keyline design
* Landscape architecture
* Sustainable
* Landscape design
* Spatial design
* Urban design

Industrial
design|

* Automotive design
* Automotive suspension design
* CMF design
* Corrugated box design
* Electric guitar design
* Furniture design
* Sustainable
* Hardware interface design
* Motorcycle design
* Packaging and labeling
* Photographic lens design
* Product design
* Production design
* Sensory design
* Service design

Interaction
design|

* Experience design
* EED
* Game design
* Level design
* Video game design
* Hardware interface design
* Icon design
* Immersive design
* Information design
* Interactive design
* Sonic interaction design
* User experience design
* User interface design
* Web design

Other
applied arts|

* Public art design
* Ceramic / glass design
* Fashion design
* Costume design
* Jewellery design
* Floral design
* Game art design
* Property design
* Scenic design
* Sound design
* Stage/set lighting design
* Textile design

Other
design
& engineering|

* Algorithm design
* Behavioural design
* Boiler design
* Database design
* Drug design
* Electrical system design
* Experimental design
* Filter design
* Geometric design
* Work design
* Integrated circuit design
* Circuit design
* Physical design
* Power network design
* Mechanism design
* Nuclear weapon design
* Nucleic acid design
* Organization design
* Process design
* Processor design
* Protein design
* Research design
* Social design
* Software design
* Spacecraft design
* Strategic design
* Systems design
* Test design

Approaches

* Active
* Activity-centered
* Adaptive web
* Affective
* Brainstorming
* By committee
* By contract
* C-K theory
* Closure
* Configuration
* Contextual
* Continuous
* Cradle-to-cradle
* Creative problem-solving
* Creativity techniques
* Critical
* Design fiction
* Defensive
* Design–bid–build
* Design–build
* architect-led
* Diffuse
* Domain-driven
* Ecological design
* Energy neutral
* Engineering design process
* Probabilistic design
* Ergonomic
* Error-tolerant
* Evidence-based
* Fault-tolerant
* Feminist
* For assembly
* For behaviour change
* For manufacturability
* For Six Sigma
* For testing
* For the environment
* For X
* Framework-oriented
* Functional
* Generative
* Geodesign
* HCD
* High-level
* Hostile
* Inclusive
* Integrated
* Integrated topside
* Intelligence-based
* Iterative
* KISS principle
* Low-level
* Metadesign
* Mind mapping
* Modular
* New Wave
* Object-oriented
* Open
* Over
* Parametric
* Participatory
* Platform-based
* Policy-based
* Prevention through
* Process-centered
* Public interest
* Opinion poll
* Public opinion
* Rational
* Regenerative
* Reliability engineering
* Research-based
* Responsibility-driven
* RWD
* Safe-life
* Speculative
* Sustainable
* Systemic
* SOD
* Tableless web
* Theory of constraints
* Top-down and bottom-up
* Transformation
* Transgenerational
* TRIZ
* Universal
* Design for All
* Usage-centered
* Use-centered
* User-centered
* Empathic
* User innovation
* Value-driven
* Value sensitive
* Privacy by
* Quality by
* Secure by

* Design choice
* computing
* controls
* culture
* flow
* justice
* leadership
* management
* marker
* methods
* pattern
* research
* science
* sprint
* strategy
* theory
* thinking

* Tools
* Intellectual property
* Organizations
* Awards

| Tools|

* AAD
* Architectural model
* Blueprint
* Comprehensive layout
* CAD
* CAID
* Virtual home design software
* CAutoD
* Design quality indicator
* Electronic design automation
* Flowchart
* Mockup
* Design specification
* Design system
* Prototype
* Sketch
* Storyboard
* Technical drawing
* HTML editor
* Website wireframe

|

Intellectual
property|

* Clean-room design
* Community design
* Design around
* Design infringement
* Design patent
* Fashion design copyright
* Geschmacksmuster
* Industrial design rights
* European Union

Organizations|

* American Institute of Graphic Arts
* Chartered Society of Designers
* Design and Industries Association
* Design Council
* International Forum Design
* Design Research Society

Awards|

* European Design Award
* German Design Award
* Good Design Award (Museum of Modern Art)
* Good Design Award (Chicago Athenaeum)
* Graphex
* IF Product Design Award
* James Dyson Award
* Prince Philip Designers Prize

Related topics

* Agile
* Concept art
* Conceptual design
* Creative industries
* Cultural icon
* .design
* Dominant design
* Enterprise architecture
* Form factor
* Futures studies
* Indie design
* Innovation management
* Intelligent design
* Lean startup
* New product development
* OODA loop
* Philosophy of design
* Process simulation
* Reference design
* Slow design
* STEAM fields
* Unintelligent design
* Visualization
* Wicked problem

* Design attributes
* brief
* change
* classic
* competition
* architectural
* student
* director
* education
* elements
* engineer
* firm
* history
* knowledge
* language
* life
* load
* museum
* optimization
* paradigm
* principles
* rationale
* review
* specification
* studies
* studio
* technology

*[v]: View this template
*[t]: Discuss this template
*[e]: Edit this template