## “Code Contracts Succinctly” Free E-Book

Syncfusion is an interesting company that publishes a series of free e-books. Each e-book has about 100 pages and is a free PDF download if you register with Syncfusion. I’m always skeptical about “free” but I’ve worked with the Syncfusion folks and like them a lot.

Anyway, Syncfusion recently released “Code Contracts Succinctly”. See https://www.syncfusion.com/resources/techportal/details/ebooks/csharpcontracts. The author is Dirk Strauss. I did the technical review of the manuscript (checking the code examples). In addition to being really good technically, Dirk explains things very well — just the right combination of code examples and text explanations.

Code contracts are an interesting concept and were developed for the C# language and Visual Studio by Microsoft Research. By coincidence, I actually worked with two of the guys at Microsoft Research who designed code contracts. I think the idea of code contracts is best explained by example. Suppose you have written some code that looks like:

```public void DoSomething(double x, double y)
{
double z = x / y;
. . .
```

You’d probably want to add an error-check like:

```public void DoSomething(double x, double y)
{
if (y == 0.0)
double z = x / y;
. . .
```

A code contract approach might look something like:

```public void DoSomething(double x, double y)
{
Contract.Requires(y != 0.0);
Contract.Invariant(this.foo != null);
double z = x / y;
. . .
Contract.Ensures(z >= 1.0);
```

A Requires() checks a precondition, an Ensures() checks a post-condition, and an Invariant() checks something that must be true at all steps in the method.

There’s much, much more to code contracts than this, but you should grasp the main idea.

Code contracts introduce a lot of additional code and complexity, but for complex, critical software systems, code contracts could be worth the effort.