Use. NET Code Contracts for runtime verification. netcontracts

Source: Internet
Author: User

Use. NET Code Contracts for runtime verification. netcontracts

The Contract class library of. NET is part of the Declarative Programming Practice and can bring many benefits to daily Programming:

  • To improve code readability, the user can see the input and output received by the Require method.
  • Reduce repeated Verification Code
  • With third-party tools, you can easily analyze static Code and unit tests to generate API documents. For more information about these functions, see the Code Contract homepage.

The Contract class itself has been integrated into the System. Diagnostics. Contracts namespace after. NET 4.0. However, if you want to use the Contract method for runtime verification, you also need to install a VS plug-in separately. After installation, go to the project properties to enable runtime check:

In this way, each time the project is compiled, the ccrewrite tool in the plug-in will compile the Contract method into a valid check code to inject the first and last sections of the function body respectively. Therefore, even if you put the Contract. Ensures check at the beginning of the function (this is recommended), after compilation, the logic will still appear at the end of the function and check whether the function termination condition is met.

Note that,If you want to use the Runtime verification function in both Debug and Release Build, you must enable Runtime check when the project is set to Debug and Release compilation.

The basic usage of Contract includes Requires and Ensures. Requires checks whether the initial conditions are met at the beginning of the method and is usually used for parameter verification. The Ensures method is used to check whether the execution result meets the expectation at the end of the method. For example, it can be placed at the end of the Property set method to check whether the Property is correctly set.

When the check fails, ContractException is thrown by default. You can specify other types of exceptions by using generic Requires and EnsuresOnThrow.

        public async void GetPage(string entryPageUrl)        {            Contract.Requires<ArgumentException>(Uri.IsWellFormedUriString(entryPageUrl, UriKind.Absolute));            ...        }

 

Contract has a cool feature, that is, some checks can be defined in the interface, requiring all implementations to meet these check entries, in this way, you do not need to define the same check logic in each implementation of the interface. This is very elegant and meets the original intention of Declaration Programming.

The following is the sample code:

    [ContractClass(typeof(IBookRepositoryContract))]    public interface IBookRepository    {        string BookTitle { get; set; }        void Create(string name, Stream blob);    }    [ContractClassFor(typeof(IBookRepository))]    sealed class IBookRepositoryContract : IBookRepository    {        public string BookTitle        {            get            {                return null;            }            set            {                Contract.Requires(!string.IsNullOrWhiteSpace(value), "Book title must not be empty.");                Contract.Requires(string.IsNullOrWhiteSpace(this.BookTitle), "Book title has already been set.");            }        }        public void Create(string name, Stream blob)        {            Contract.Requires<InvalidOperationException>(!string.IsNullOrWhiteSpace(this.BookTitle), "Book title hasn't been set");        }    }

In this way, all IBookRepository implementation classes do not need to define these checks.

 

References:

Http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf

Http://blog.csdn.net/atfield/article/details/4465227

Http://www.cnblogs.com/yangecnu/p/The-evolution-of-argument-validation-in-DotNet.html

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.