Use the code contract to write better code and better code Contract writing
(This article is also published in my public account "dotNET daily excellent article". Welcome to the QR code on the right to follow it .)
Question: there are many ways to write better code, one of which is to add a contract to the code. The recommended article today introduces the use of the open-source Code Contract tool Library released by Microsoft Research Institute.
The so-called code contract allows you to use additional code to express the assumptions of the Business Code in the application. Generally, You can execute pre-condition judgment, post-condition judgment, and object immutable judgment. Microsoft Research Institute provides this tool for. NET, namely, Code Contracts for. NET, an extension tool of VS (only version 2013 is supported now ). After installing this tool, you can see an additional tab in the project properties, as shown in:
We can see that we can perform two types of checks: runtime check and static check. This is two of the three major functions provided by Code Contracts for. NET, and one is the document generator.
Runtime check
This function provides a binary rewriting tool to inject your code contract into the program, so that you can check the program during execution. This type of rewriting program also improves testing because each contract acts as an oracle and can predict whether the test may pass. At the same time, some automation tools, such as Pex, can also use contracts to generate more meaningful unit tests, because meaningless unit tests that do not meet the pre-condition judgment do not need to be generated.
Static check
This function provides a static Checker to determine whether a contract is violated even if the program is not running. It can check both implicit contracts, such as empty references and array boundaries, and explicit contracts.
Document Builder
This function can place the contract information in the existing code comment xml document.
In my opinion, code contracts are somewhat similar to assertions, but they are more powerful than assertions. They are also similar to unit tests, but they are also a supplement to unit tests based on the underlying layer.
This article by Dirk Strauss has simple and clear sample code and is intuitive. It is a good getting started tutorial for the use of this tool. Read the original article to access this article.
Address: http://www.dirkstrauss.com/programming/introducing-code-contracts#.VWCNlvnvO70