Design by contract
wikipedia Design by contract
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.
History
Design by contract has its roots in work on formal verification, formal specification and Hoare logic.
Description
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
Performance implications
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.
Language support
Languages with native support
Contract and aspect
Contract 更多是理念层、而aspect则是如何实现,在 "wikipedia Design by contract # Languages with third-party support" 中给出了一些通过AOP来实现contract的例子:
1、JavaScript, via AspectJS
2、Java
编写可以发现问题的代码
Design by contract能够帮助我们"编写可以发现问题的代码",对于一些错误情况,程序员需要能够提前断言,然后将这些断言编码到程序中,当此断言成真,即程序进入到了这个分支,需要使用适当的方式通知,不同的编程语言提供了不同的通知方式:
1、python可以raise Exception
关于断言,参见:Assertion
章节。