Design by contract
From Wikipedia, the free encyclopedia
Design by contract, DBC or Programming by contract is a methodology for designing computer software. It prescribes that software designers should define precise checkable interface specifications for software components based upon the theory of abstract data types and the conceptual metaphor of a business contract.
Contents |
[edit] 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 [1] [2] [3] and the two successive editions (1988, 1997) of his book Object-Oriented Software Construction.
Design by contract has its root 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 methodology for redefinition and dynamic binding.
- The application to exception handling.
- The connection with automatic software documentation.
"Design by Contract" is a trademark of Eiffel Software (part of Interactive Software Engineering Inc. or ISE), the designers of Eiffel.
[edit] 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" which defines for example that:
- The supplier has to 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 a routine from a class in object-oriented programming provides a certain functionality, it may:
- Impose a certain obligation to be guaranteed on entry by any client module that calls it: the routine's precondition — an obligation for the client, and a benefit for the supplier (the routine itself), as it frees it from having to handle cases outside of the precondition.
- Guarantee a certain property on exit: the routine's postcondition — an obligation for the supplier, and obviously a benefit (the main benefit of calling the routine) for the client.
- Maintain a certain property, assumed on entry and guaranteed on exit: the class invariant.
The contract is the formalization of these obligations and benefits. One could summarize design by contract by the "three questions" that the designer must repeatedly ask:
- What does it expect?
- What does it guarantee?
- What does it maintain?
Many languages have facilities to make assertions like these. However, DBC is novel in recognizing that these contracts are so crucial to software correctness that they should be part of the design process. In effect, DBC advocates writing the assertions first.
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 (compare to type bounds for Java 5 generics), and their meanings
- Return values or types (compare to type bounds for Java 5 generics), and their meanings
- Error and exception conditions values or types (compare to type bounds for Java 5 generics), that can occur, and their meanings
- Side effects
- Preconditions
- Postconditions
- Invariants
- (Rarer) Performance guarantees, e.g. for time or space used
Using the DBC methodology, the program code itself must never try to verify the contract conditions; the whole idea is that code should "fail hard", with the contract verification being the safety net. DBC's "fail hard" property makes debugging for-contract behavior much easier because the intended behaviour of each routine is clearly specified.
The contract conditions should never be violated in program execution: thus, they can be either left in as debugging code, or removed from the code altogether for performance reasons.
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.
Unit testing tests a module in isolation, to check that it meets its contract assuming its subcontractors meet theirs. Integration testing checks whether the various modules are working properly together. Design by contract also fosters code reuse, since the contract for each piece of code is fully documented. The contracts for a module can also be regarded as a form of software documentation for the behavior of that module.
[edit] Non-technical analogy
A process in which a number of objects (people or software components, for example) interact to satisfy a goal is called a collaboration. When two objects collaborate together, one - the client - requests the services of the other - the supplier. The supplier in turn may request the sevices of other objects, and in those collaborations it is the client and they are the suppliers. The process only works correctly if all these individual collaborations work correctly. In a very real sense, the chain is only as strong as its weakest link.
Take the process of going on holiday, for example. Bertrand wants to spend two weeks in Florida. He books the holiday through DBC Holidays Inc., who specialise in U.S. package holidays. When he makes the booking (collaboration #1), Bertrand is the client and DBC Holidays are the supplier. DBC Holidays then arrange flights through Assertair Corp. (collaboration #2), and book a room at the Precondition Plaza Hotel in Miami (collaboration #3). In collaboration #2, DBC Holidays are the client and Assertair is the supplier, and in collaboration #3, the hotel is the supplier. And the chain of collaborations goes deeper and deeper (e.g., who does Assertair pay to service their jets?)
If any link in this chain of collaborations breaks, then the upshot could be that Bertrand's holiday is ruined. It's vital, therefore, that every player in the collaboration does what they're supposed to do. In any collaboration, client and supplier have certain obligations. These obligations (or "responsibilities", if you like) fall into three distinct types:
- Things that the supplier promises to do as part of the service it offers to the client (e.g., Assertair promises DBC Holidays that Bertrand will be in Miami at a certain date and time)
- Things that the client promises to do before using the service (e.g., DBC Holidays must ensure that Bertrand has his passport and tickets when he checks in for his flight)
- Things that the supplier promises will always be true no matter what happens (e.g., The airline will always have adequate insurance to cover any accident)
Things that the supplier promises to do as part of the service are described as a special kind of rule called a postcondition. The postcondition tells the client what will be true if the service is executed correctly (e.g., "your customer will be in Miami by 15:30 on June 8").
If Bertrand turns up at the check-in desk without his passport, of course, then the airline can't live up to their side of the contract - he will not be allowed to board the plane without it. A rule that the client must satisfy before using a service is called a precondition.
A rule that states what must always be true is called an invariant. If the airline doesn't have adequate insurance then nobody is going anywhere!
Design By Contract is a discipline for building software such that the collaborations between objects are correct. A formula for correctness when a client uses the services of a supplier is given as:
If the invariant AND precondition are true before using the service, then the invariant AND the postcondition will be true after the service has been completed.
In DBC, the responsibilities are clear: the client must satisfy the precondition. This distinguishes it markedly from a related practice known as 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 - the client must figure out how to respond to that. DBC makes the supplier's job easier.
[edit] Languages implementing DBC
[edit] C
Recent efforts add support for Design by Contract to the C programming language using DBC for C, a preprocessor written in Ruby.
Other tools supporting DBC for C include:
[edit] C++
Tools supporting DBC for C++ include:
- C2
- Gnu nana
Libraries developed using design-by-contract:
[edit] C#
Tools supporting DBC for C# include:
- eXtensible C#, a commercial post-compiler that transforms "declarative assertions", in the form of .NET attributes attached to C# methods and properties, into actual pre- and post-conditions embedded in the compiled .NET IL code.
- Spec#, a Microsoft research extension of the C# language.
- Microsoft Visual Studio Team System for Software Testers, a Microsoft Development Environment for C# (and other .NET languages) that provides unit testing capabilities.
[edit] Chrome
The Chrome programming language is an Object Pascal implementation that has "class contracts", which are similar to DBC.
[edit] D
D implements Design by Contract as a major feature.[4]
[edit] Eiffel
The object oriented Eiffel programming language was created to implement Design by Contract. The language is organized around the concepts of Design by Contract, closely integrated with its object-oriented structure and in particular with its inheritance mechanism, with direct language support for weakening preconditions and strengthening postconditions.
Eiffel compilers support run-time assertion monitoring through a compilation option. A run-time assertion violation triggers an exception. The exception mechanism is, more generally, directly based on the concepts of Design by Contract.
[edit] Java
Tools supporting DBC for Java include:
- iContract2, a free Java source pre-processor/code-generator that uses Javadoc tags to specify preconditions, postconditions, and invariants
- Contract4J, a DBC tool where tests are defined using Java 5 annotations and aspects written in AspectJ evaluate the test expressions at runtime and handle failures.
- jContractor, which provides runtime contract checking by instrumenting the bytecode of classes that define contracts
- Jcontract, a proprietary DBC tool by Parasoft
- C4J, an open source tool with full support for contract inheritance and also the possibility to define contracts for interfaces
- CodePro Analytix, which generates unit test case logic in Eclipse based on assertions within the class and method Javadocs.
- STclass is an open source Contract Based Built-in Test (CBBT) Framework; it allows the definition of contracts and test-units in classes and interfaces and handles contracts and test-units inheritance.
- Jass, a GPLed Java source pre-processor that uses specially formatted Java comments to specify preconditions, postconditions, and invariants, ...
- SpringContracts, is an open source solution with seamless integration into the Spring Framework. It is mainly based on AOP, Annotations and an exchangeable specification language (EL, OGNL, Groovy) for contract definition.
[edit] JML
The Java Modeling Language (JML) provides specifications, including contracts, to describe Java programs.
[edit] Lisaac
Lisaac implements Design by Contract as a major feature.
[edit] Nemerle
Nemerle implements Design by Contract as a major feature.
[edit] Perl
Damian Conway's Class::Contract module, now maintained by C. Garrett Goebel, is available from CPAN, and implements design-by-contract in Perl. Although the module is not widely used, it enjoys some popularity among Perl users involved in larger projects. Class::Agreement is a newer, less mature alternative.
[edit] Perfect
Escher Technologies' specification language Perfect, as used in the software development tool Perfect Developer implements an extension of DBC, which is called Verified Design by Contract, or VDBC. This tool enjoys popularity with students on some computer science courses as it can generate working programs in Java.
[edit] PHP
PHP can implement design by contract via its assert() function and a callback function defined using assert_options().
[edit] PLT Scheme
PLT Scheme, an extension of the Scheme programming language, implements a sound variant of Eiffel's DBC for modules, higher-order functions, and objects. The design of this system emphasizes that each contract violation must blame the guilty party and must do so with an accurate explanations. Findler and Felleisen's papers carefully explain that this is not the case for Eiffel's system.
[edit] Python
Python supports DBC through tools like PyDBC, Contracts for Python, and Dmitry Dvoinikov's recipe.
[edit] Ruby
There are several external Design by Contract modules available for Ruby, including DesignByContract, Ruby DBC, and ruby-contract.
[edit] Sather
The Sather programming language implements Design by Contract.
[edit] SPARK
The SPARK programming language implements Design by Contract by static analysis of Ada programs. By using static analysis SPARK ensures that no contract is ever broken at run-time. This means that Eiffel's problematic 'fail hard' situation will never occur on SPARK.
[edit] See also
- Defensive programming
- D programming language
- Eiffel programming language
- Hoare logic
- Object-Oriented Software Construction
- Perfect specification language
- SPARK programming language
- Test-driven development
[edit] Bibliography
- ^ 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, pages 40-51, also available online
- ^ Bright, Walter (2006-08-20). D Programming Language, Contract Programming. Digital Mars. Retrieved on 2006-10-06.
- Mitchell, Richard, and McKim, Jim: Design by Contract: by example, Addison-Wesley, 2002
- A wikibook describing DBC closely to the original model.
[edit] External links
- An introduction to Design by Contract(TM)
- Original IEEE Computer article
- Isaac / Lisaac Project home
- C2 Wiki: Design by contract
- Damian Conway's Class::Contract Perl module from CPAN
- dlib C++ Library A C++ library that uses the DBC methodology
- SpringContracts SpringContracts is a Java Solution for Design By Contract with seamless integration into the Spring Framework.