Monday, April 20, 2015

Code Contracts

The term ‘code contract’ was coined by Bertrand Meyer while he was developing the Eiffel programming language around 1986.

Code contracts and unit tests are not replacements for each other. They both have different purpose and different nature. It does not matter if you are using code contracts or not – you still have to write tests for your code.

The contracts take the form of pre-conditions, post-conditions, and object invariants. Contracts act as checked documentation of your external and internal APIs. The contracts are used to improve testing via runtime checking, enable static contract verification, and documentation generation. Code Contracts bring the advantages of design-by-contract programming to all .NET programming languages.

Automatic testing tools, such as Pex, take advantage of contracts to generate more meaningful unit tests by filtering out meaningless test arguments that don't satisfy the pre-conditions. Code contracts can be found in the System.Diagnostics.Contracts namespace.

using System;
using System.Diagnostics.CodeContracts;
namespace Products.BusinessLayer{
public class ProductName{
private string name;

public ProductName(string name)
{
Contract.Requires(
!string.IsNullOrWhiteSpace(name)
);
Contract.Ensures(!string.IsNullOrWhiteSpace(this.name));
this.name = ChangeName(name);
}
}
}

Technorati Tags: ,,

No comments:

Post a Comment