Comparison: DbC and TDD – Part 3

This blog post is a continuation of the comparison between DbC and TDD that started with a dedicated look at code specification and covered other aspects in part 1 and part 2. It takes a look at further points and shows the characteristics (commonalities and differences) of TDD and DbC towards these aspects.

Universality

One of the most important differences between DbC and TDD is their different universality, because it influences expressiveness as well as verifiability of correctness.

A significant limitation (or better characteristic) of TDD is that tests are example-driven. With a normal manually written unit test you provide exemplaric input data and check for certain expected output values after the test run. Thus you have concrete pairs of input/output values to express a certain feature/behavior that you want to test. Since these values are only examples there has to be a process of finding relevant examples which can be very difficult. One step towards correctness is high code coverage. You should find examples that examine all paths of your code components. That can be a mess since the amount of possible code paths grows exponentially with the count of branches (if, switch/case, throw, …). But even if you find examples that give you 100% code coverage you cannot be sure that the component acts right for all possible input values. On the one side there could be hardware-dependent behavior (e.g. with arithmetic calculations) that leads to differences or exceptions (division-by-zero, underflow/overflow etc.). On the other side perhaps you get 100% code coverage for your components during the TDD process, but this doesn’t help much on integration with other code components or external systems that could act in complex ways. This problem goes beyond TDD. Thus unit tests in a TDD fashion are nice by their flexibility and simplicity, but they cannot give you full confidence. Solutions like Pex can help you here, but this is part of another story (that I hope to come up with in the near future).

DbC on the other side introduces universal contracts that must hold for every value that an object as part of a contract can take. That’s an important aspect to ensure correct behavior in all possible cases. Thus contracts have a higher value in terms of universality than tests (but they fall back in other terms).

Expressiveness

The expressiveness of a component’s behavior and qualities as part of its specification is an important aspect since you want to be able to express arbitrary properties in a flexible and easy way. Universality is one part of expressiveness and has just been discussed. Now let’s look at expressiveness on a broader scope.

TDD has a high value on expressiveness besides the exemplaric nature of tests. You are free to define tests which express any desired behavior of a component that can be written in code. With TDD you have full flexibility, but you are also responsible to get this flexibility under your control (clear processes should be what you need). One aspect that goes beyond the scope of TDD is interaction/collaborative testing and integration testing. The TDD process implies the design of code components in isolation, but it doesn’t guide you in testing the interactions between components (and specification of behavior which relies on those interactions). TDD is about unit testing, but there is a universe beyond that.

Their universal nature makes contracts in terms of DbC a valuable tool. And moreover by extending the definition of a code element they improve the expressiveness of these code elements, what’s great e.g. for the role of interfaces and for intention revealing. But they have downsides as well. First they are tightly bound to a certain code element and are not able to express behavior that spans several components (e.g. workflows and classes interacting together). And second they have a lack of what I would call contentual expressiveness. With contracts you are able to define expectations with arbitrary boolean expressions and that’s a great thing. But it’s also a limitation. For example if you have an algorithm or complex business operation then it’s difficult to impossible to define all expected outcomes of this code as universal boolean postcondition. In fact this would lead to full functional specification which implies a duplication of the algorithm logic itself (in imperative programming) and this would make no sense! On the other side if you use example-driven tests you would not have a problem since you should know what values to expect on a certain input. Furthermore no side effects are allowed inside of a contract. Hence if you use a method to define a more complex expectation this method must be pure (= free of visible side effects). The background of this constraint is that contracts mustn’t influence the behavior of the core logic itself. It would be a mess if there would be a different behavior depending on the activation state (enabled/disabled) of contracts (e.g. for different build configurations). This has a limitation if you want to define certain qualitites with contracts like x=pop(push(x)) for a stack implementation, but it has advantages as well, since it leads to the enforcement of command-query separation by contracts.

Checking correctness

Of course you want to be able to express as many behaviors as possible to improve the specification of your code components. But expressiveness is not leading anywhere when it’s impossible to figure out if your components follow the defined specification. You must be able to stress your components against their specification in a reproducible way to ensure correct behavior!

With TDD correctness of the defined behavior (= tests) can be checked by actually running the tests and validating expected values against the actual values as outcome of a test run. The system-under-test is seen as blackbox and behavior correctness is tested by writing values to the input channels of the blackbox and observe the output channels for correct values. This could include techniques like stubbing or mocking for handling an object in isolation and for ensuring reproducible and verifiable state and behavior. This testability and reproducibility in conjunction with a well implemented test harness is important for continuously checking correctness of your code through regression testing. It’s invaluable when performing continuous integration and when code is changed, but this aspect will be covered in the next blog post. However the exemplaric nature of tests is a limitation for checking correctness which has been shown above when discussing universality.

At first DbC as principle doesn’t help you in terms of checking correctness. It introduces a fail-fast strategy (if a contract is not met, it’s a bug – so fail fast and hard, because the developer has to fix the bug), but how can you verify the correctness of your implementation? With DbC bugs should be found in the debugging step when developing code, thus by actually executing the code. And common solutions like Code Contracts for .NET come with a runtime checking component that checks the satisfaction of the defined contracts when running the code. But this solution has a serious shortcoming: It relies on the current execution context of your code and hence it takes the current values for checking the contracts. With this you get the same problems as with tests. Your contracts are stressed by example and even worse you have no possibility to reproducible check your contracts! Thus dynamic checking without the usage of tests makes no sense. However contracts are a great complement of tests. They specify the conditions that must apply in general and thus a test as client of a component can satisfy the preconditions and then validate postconditions or custom test behavior. Another interesting possibility to verify contracts is static checking. Code Contracts come with a static checker as well that verifies the defined contracts at compile-time without executing the code. On the contrary it actually inspects the code (gathers facts about it) and matches the facts as abstraction of the implementation against the defined contracts. This form of whitebox code inspection is done by the abstract interpretation algorithm (there are other solutions like Spec# that do real formal program verification). The advantage of static checking is that it’s able to find all possible contract violations, independent of any current values. But static checking is hard. On the one side it’s hard for the CPU to gather information about the code and to verify contracts. Hence static checking is very time-consumptive which is intolerable especially for bigger code bases. On the other side it’s hard for a developer to satisfy the static checker. To work properly static checking needs the existence of the right (!) contracts on all used components (e.g. external libraries) which is often not the case. And looking at the static checker from Code Contracts it seems to be too limited at the current development state. Many contracts cannot be verified or it’s too impractical to define contracts that satisfy the checker. Thus static checkers are a great idea to universally verify contracts, but especially in the .NET world the limitations of the checkers make them impractical for most projects. Hence a valid strategy for today is to write tests in conjunction with contracts and to validate postconditions and invariants with appropriate tests.

[To be continued…]

kick it on DotNetKicks.com

Comparison: DbC and TDD – Part 2

This blog post is a continuation of the comparison and differentiation between DbC and TDD. Please take a look at part 1 which covers the design aspect (and shortly specification again which has been discussed in more detail here). Today’s post takes a look at documentation and code coupling and shows commonalities and differences of TDD and DbC towards these aspects.

Documentation

One important thing for other developers to understand your code is documentation. Code comments are a first necessity here to basically explain what a code component is intended to do. But comments have the unpleasant habit to run out-of-sync with the real code if you are not carefully and consequently adapting them. Most of all if you write obligations or benefits into comments there will be no check if those requirements hold or if the real implementation matches them.

DbC with its contracts is a much better way to document those specification aspects. Contracts are coupled to the code and e.g. with Code Contracts you get static and runtime checking for them. This checked documentation makes DbC really powerful (if properly used) and avoids the asynchronicity between code and documentation. It shows developers how a component should be used, what requirements the client  has to fulfill and what he can expect in return. The client can rely on these specified qualities which improves the reusability of contracted code components. Furthermore there are possibilities to integrate Code Contracts into the Sandcastle documentation and for Visual Studio 2010 there will be an add-in that immediately shows defined contracts on a component as you develop against it. With that you get great MSDN-like documentation that contains the defined contracts as well as support for your development process when you use contracted code.

Tests in terms of TDD add another aspect of documentation. Due to their exemplary nature and their specification of an element’s behavior those tests are great to show a developer the intent of a code component and give him a guideline to its usage. Since tests can be run and validated in a reproducible way developers are able to rely on defined behaviors as well.

Together with documentation comes the aspect of intention revealing. And both TDD and DbC add some value here. Both express the developer’s intention with a certain component and show far beyond code comments and naming conventions what behavior a client can expect. Developers can use the component in these specified ways and don’t have to manually investigate the component’s implementation.

Code coupling

One drawback of TDD is the locational gap between the code implementation and the tests as specification and documentation source. For sure this has an advantage as well: the code logic isn’t polluted with the specification and thus it’s kept clean. But the disadvantages weigh heavier for me. If developers want to show how a component behaves they have to cross the gap and investigate the tests. This is difficult for developers who are not very familiar with TDD. Furthermore tests don’t give any support for client usage of a component. Of course they give usage examples, but developers can use and especially misuse a component in arbitrary ways. This can lead to serious problems (e.g. inconsistent states) if there are no other mechanisms to prohibit misusage.

DbC on the other side sets contracts directly on the implementation of a code component in place. Thus they have a declarative nature and extend the definition of a code component. Some realizations of DbC like Code Contracts in .NET have drawbacks since they set contracts imperatively into the code, but rewrite the code after compilation to set the contracts in the „right“ places. Thus Code Contracts break the uniformity principle (different semantics should be expressed through different syntax) and pollute the code logic in some way. Other realizations like the Eiffel language have contracts as keywords built into the language which makes a better choice in my opinion. Anyway contracts at the same place as the implementation avoids the drawbacks of a locational gap. And moreover DbC prevents misusage of a component. Contracts are dynamically checked at runtime or statically at compile time and fail early if requirements are not satisfied. That’s a very important concept because it expresses a clear behavior if something goes wrong (existence of a bug) and gives a clear contract for obligations and benefits that hold and are checked in client/supplier communication.

[To be continued…]

kick it on DotNetKicks.com

Comparison: DbC and TDD – Part 1

Let’s come to another blog post in preparation of elaborating the synergy of DbC and TDD. My first blog post on this topic covered an initial discussion on specification of code elements. Thereby it has shown different characteristics of DbC and TDD in terms of code specification. Since specification is one really important aspect in comparison of DbC and TDD, it’s of course not the only one. Hence today’s blog post is a starting point for a more general comparison of DbC and TDD with some other important aspects. There are 3 more blog posts that I will come up with during the next weeks, forming a 4-part comparison series.

To say first, Test-Driven Development (TDD) and Design by Contract (DbC) have very similar aims. Both concepts want to improve software quality by providing a set of conceptual building blocks that allow you to prevent bugs before making them. Both have impact on the design or development process of software elements. But both have their own characteristics and are different in achieving the purpose of better software. It’s necessary to understand commonalities and differences in order to take advantage of both principles in conjunction.

Specification again…

The last blog post has already given a dedicated look at the specification aspect and how DbC and TDD can add some value. To summarize both principles extend the code-based specification in their own ways. TDD let’s you specify the expected behavior of a code element in an example-driven and reproducible way. It’s easy to use and allows the expression of any expected behavior. DbC on the other side sets universal contracts in place that extend the definition of a code element and are tightly coupled to it. It’s a great concept for narrowing the definition of a code element by defining additional physical constraints as preconditions, postconditions and invariants. By defining contracts on interfaces DbC strengthens the role of interfaces and enforces identical constraints/behavior over all implementations of an interface. However not every behavior can be expressed by contracts and they’re bound to a single code element. Thus they don’t lessen the position of tests, but can be seen as great complement.

Design aspect

Both DbC and TDD have impact on the design of an API. Well, there is a slight but important difference as the names imply: it’s Design by Contract, but Test-Driven Development. Thus with DbC (contract-first) on the one side you are encouraged to write your contracts as you design your components (at design phase), which perfectly fits with the idea of contracts as extension of a component’s definition. With TDD and the test-first principle on the other side you write a test which maps to a new feature and afterwards you directly implement the code to get the test to green state. Hence TDD is tightly coupled to the development phase in contrast to DbC, which seems to come first. In addition personally I wouldn’t fight a religious war on this naming. If you think of DbC as „Contract-First Development“ or „Development by Contract“ you would have the contract-first principle coupled to the development phase as well. The more important thing is to find a way to effectively use contracts in the development cycle. If you are an advocate of up-front design you would perhaps want to set your contracts at design phase. But if you intensively use TDD it would be difficult to go down this design phase road. However you would set your contracts at development phase in conjunction with the test-first principle. This leads to the question of an effective development model with TDD and DbC and that’s another important story…

But for now let’s come back to the impact of DbC and TDD to the design of an API. With TDD you write a new test for each new feature and then you bring this test to green by implementing some piece of logic. This is some form of Client-Driven Development. Your test is the client of your API and you call your methods from the client’s perspective (as a client would do). If the current API doesn’t fit your needs, you extend or modify it. Thus the resulting API is very focussed on the client’s needs and furthermore doesn’t contain code for unnecessary features, which is a great thing in terms of YAGNI. Another impact of TDD is that it leads to loosely coupled components. Tests in form of unit tests are very distinct and should be coupled to the tested component, but not far beyond that (other components that are called, e.g. data access). Thus there is a certain demand for loose coupling e.g. by DI.

With DbC and contracts on your components you have other impacts. Contracts clarify the definition and intent of your components. When you come up with contracts you strengthen your opinion about a component by setting contractual obligations and benefits. This leads to much cleaner components. Moreover your components will have fewer responsibilities (and thus a better cohesion) since it would be painful to write contracts for components with many different responsibilities. Thus DbC is great in terms of supporting the SRP and SoC. Another impact comes from the „limitation“ of contracts to support only pure methods as part of a contract. If you want to use class methods in contracts (e.g. invariants) of this class you have to keep those methods pure. This leads to the enforcement of command-query separation by contracts, which very often is a good thing in terms of comprehensibility and maintainability.

[To be continued…]

kick it on DotNetKicks.com

Specification: By Code, Tests and Contracts

Currently I’m taking further investments in thinking about the synergy of Design by Contract (DbC) and Test-Driven Development (TDD). This process is partially driven by my interests in Code Contracts in .NET 4.0 and other current developments at Microsoft (e.g. Pex). The basic idea I’ve got in mind is to combine DbC and TDD to take best advantage of both principles in order to improve software quality on the one side and to create an efficient development process on the other side. My thoughts on this topic are not too strong at the moment, so feel free to start a discussion and tell me what you think.

Before I come to discuss the synergy of DbC and TDD it’s absolutely necessary in my opinion to understand the characteristics, commonalities and differences of both concepts. This first blog post drives in this direction by looking at a very important aspect of both concepts: the formal and functional specification of code. It’s a starting point for further discussions on this topic (a 4part comparison series follows). So let’s start…

Code-based specification

In essence, DbC and TDD are about specification of code elements, thus expressing the shape and behavior of components. Thereby they are extending the specification possibilities that are given by a programming language like C#. Of course such basic code-based specification is very important, since it allows you to express the overall behavior and constraints of your program. You write interfaces, classes with methods and properties, provide visibility and access constraints. Furthermore the programming language gives you possibilities like automatic boxing/unboxing, datatype safety, co-/contravariance and more, depending on the language that you use. Moreover the language compiler acts as safety net for you and ensures correct syntax.

Since such basic specification is necessary to define the code that should be executed, it has a lack of expressiveness regarding the intent of a developer and there is no way to verify correct semantics of a program with it. As an example interfaces define the basic contract in terms of method operations and data, but looking at C# a client of this interface does not see what the intent of a method is or which obligations he has to fulfill when calling a method or what state he can assume on return of a method. Furthermore interfaces can not guarantee uniform behavior across their implementations. TDD and DbC are there to overcome or at least decrease this lack of expressiveness at some points and to guarantee correct semantics.

Test-based specification

Let’s come to test-based specification using TDD (as well as BDD as „evolutional step“ of TDD). This is inevitably integrated in the TDD cycle. Every test written by a developer maps to a new feature he wants to implement. This kind of specification is functional and example-driven, since a developer defines by exemplary input/output pairs what output he expects as result of the test run under a certain input. With well-known techniques (stubs, mocks) he is able to run his tests in isolation, get reproducible test results and perform state and behavior verification.

Compared to code-based specification, test-based specification in a TDD manner is very valuable when it comes to expression of the behavior of a code element. It gives a set of tests that could at its extreme span the whole behavior of a code element. With their reproducibility the tests are indispensable when it comes to continuous integration to ensure correct behavior of modified code elements. Furthermore tests are a great source for other developers to show the intent of a developer for a method’s behavior and to give demonstration of the usage of a code element. There are other benefits and characteristics of TDD that will be discussed when comparing TDD and DbC altogether in subsequent blog posts.

An important aspect of test-based specification using TDD is that it’s done at a very granular level. For each new feature a test is written and if the present API doesn’t fit the needs, it will be extended or refactored. Thus TDD drives the API design as you go with your tests.

Contract-based specification

Another possibility for specifying code is contract-based specification in terms of DbC, thus defining preconditions and postconditions as method contract and invariants as class contract. With contracts you are able to define the basic obligations that a client must fulfill when calling a method as well as the benefits he gets in return. Furthermore invariants can be used to define basic constraints that ensure the consistency of a class. Thus with DbC a developer is able to define a formal contract for code that makes a clear statement of obligations and benefits in client/supplier communication (aka caller/callee). If a contract fails the behavior is clear as well: by failing fast the developer can be sure that there is a problem (bug) with his code and he has to fix it.

On a technical level there are several possibilities to define contracts. In Eiffel contracts are part of the programming language itself in contrast to Code Contracts that become part of the .NET framework. In any case contracts are directly bound to the code that they are specifying and express additional qualities of the code. Those qualities go beyond the code-based specification. In general contracts allow arbitrary boolean expressions what makes them a very powerful and flexible specification source. Nonetheless contracts only allow partial functional specification of a component. It can be very difficult or even impossible to define the complex behavior of a method (which methods is it calling, what business value does it have, what’s the concrete result for a concrete input, …) or to ensure certain qualities (e.g. infrastructure-related questions like „is an e-mail really sent?“) with contracts. Furthermore it’s impossible to use impure functions in contracts which would be necessary to express certain qualities of code (like expressing inverse functions: x = f-1(f(x)), if f or f-1 are impure). Test-based specification could be used here instead.

But let’s come back to the technical aspect: Contracts are wonderful animals in terms of extending the code-based specification by narrowing the definition of a code element and becoming part of the element’s signature. They can be used to define general conditions, e.g. physical constraints on parameters and return types. Thereby (for example with Code Contracts) the contracts can be inherited to sub-classes while respecting the Liskov substitution principle (LSP). Moreover contracts can be defined on interfaces and thus they are a valuable tool for expressing constraints and qualities of an interface that must be respected by every implementation. With that contracts are wonderfully strengthening the role and expressiveness of interfaces and complementing code-based specification at whole.

With the tight coupling to the code, contracts give immediate support for other developers how an API should be used. They express the developer’s intent (intention revealing) for his code elements, which leads to easier comprehension and usage of those components. They give some kind of checked documentation, which again greatly complements code-based specification and leads to fewer misusage of contracted components.

In contrast to test-based specification, contracts are employed at level of whole components by employing invariants to classes and pre-/postconditions to class methods. Moreover contracts lead to components with very few dependencies (promoting the SRP) since it’s difficult to write contracts for components with many responsibilities.

First conclusion

This blog post is intended to be a first preview of what I want to come up in the next time. It has given an overview of possibilities for specification of code elements with focus on test-based and contract-based specification in terms of TDD and DbC. It has shown some commonalities and qualities of both concepts. In conclusion TDD and DbC are both valuable in terms of the specification of code elements and in revealing the developer’s intent.

In my opinion it’s by no means a „one or the other“ choice. TDD and DbC act on their own terrains with their own benefits and drawbacks. There are overlaps, but in general they can naturally complement each other. It’s time to think about ways to leverage a conjunction of both concepts, isn’t it?

[To be continued…]

kick it on DotNetKicks.com

Code Contracts: Video on the static checker

Just a short hint for today: Francesco Logozzo from the Code Contracts team has made a little introductory video on the static checker. In this video he introduces the static checker and basically describes its fundamental algorithm: abstract interpretation.

Take a look at this video and please keep giving feedback to the Code Contracts team. Those are great guys who are very open for every suggestion!

Currently I’m making my mind up on DbC and the synergy with TDD and other paradigms again, so stay tuned for further blog posts on this topic.

Merry christmas to all of you!

Code Contracts #8: Sandcastle integration

Release 1.2.20903 (4 Sep 2009) of Code Contracts comes with a nice integration of contracts on classes and methods into Sandcastle documentation! By this, Code Contracts achieve an important goal: real „checked documentation“. This short article gives an overview of how to get your Sandcastle installation to handle contracts.

1) Install Sandcastle (+DocProject)

At first, of course you need a valid Sandcastle installation. Just go to the Sandcastle project page, download the latest release and install it. I recommend installing DocProject for Sandcastle and HTML Help Workshop and Documentation as well. This gives you a nice Visual Studio integration for creating documentation by Sandcastle.

2) Patch Sandcastle with Code Contracts files

Code Contracts documentation syntax is currently not included in the Sandcastle project. In order to make Sandcastle aware of the Code Contracts documentation items, you have to patch the Sandcastle installation with the Code Contracts files. For this, there exists a folder „Sandcastle“ in the Code Contracts installation directory (default is „Program Files\Microsoft\Contracts\Sandcastle„), which contains a file „Sandcastle.zip„.

If you’ve installed Sandcastle from the MSI package, just copy the contents from the „msi\vs2005“ folder of the UIP file to the following location of your Sandcastle installation: „Program Files\Sandcastle\Presentation\vs2005\„. Now you’re done and ready to generate documentation for your contracts!

3) Set up your project

First, if you want to generate documentation for a project in Visual Studio, go to the project properties and in the „Build“ option pane, check the XML documentation file option:

Activate the "XML documentation file" option

Then, to get the contracts injected into the generated XML doc file, go to the „Code Contracts“ option pane and select both the Build a Contract Reference Assembly and the Emit contracts into XML doc file options:

Select generation of Code Contracts documentation

Now, when you build your project, first the documentation of your project’s components will be created as XML file and then the contracts documentation will be injected in the same file.

4) Create your documentation!

For demonstation purposes, I’ve generated a project (including a new solution) AccountExample in Visual Studio, which holds just one class Account. This example class contains some contracts and looks as follows:

/// <summary>
/// Represents an account, to which you can deposit and from which you can withdraw money.
/// </summary>
public class Account
{
    private float _balance;
    /// <summary>
    /// The current balance of the account.
    /// </summary>
    /// <value>The account's balance.</value>
    public float Balance
    {
        get { return _balance; }
        private set
        {
            Contract.Requires(value >= 0);
            _balance = value;
        }
    }

    [ContractInvariantMethod]
    protected void ClassInvariants()
    {
        Contract.Invariant(_balance >= 0);
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="Account"/> class.
    /// </summary>
    /// <param name="balanceInitial">The initial balance, which will be set.</param>
    public Account(float balanceInitial)
    {
        Contract.Requires(balanceInitial >= 0);
        Contract.Ensures(Balance == balanceInitial);

        Balance = balanceInitial;
    }

    /// <summary>
    /// Deposits the specified amount to the account.
    /// </summary>
    /// <param name="amount">The amount to deposit.</param>
    public void Deposit(float amount)
    {
        Contract.Requires(amount > 0);
        Contract.Ensures(Balance == (Contract.OldValue(Balance) + amount));

        Balance += amount;
    }

    /// <summary>
    /// Withdraws the specified amount from the account.
    /// </summary>
    /// <param name="amount">The amount to withdraw.</param>
    public void Withdraw(float amount)
    {
        Contract.Requires(amount > 0);
        Contract.Requires(amount <= Balance);
        Contract.Ensures(Balance == (Contract.OldValue(Balance) - amount));

        Balance -= amount;
    }
}

Moreover, I’ve added a new DocProject to my solution, where I’ve chosen the „AccountExample“ project for generating the documentation from. With that we’re ready to roll!

When building the whole solution, first the assembly of the „AccountExample“ project is built. In this step, the following XML documentation file is extracted as well (note the injected contract tags – requires, ensures and invariant):

<?xml version="1.0"?>
<doc>
  <assembly>
    <name>AccountExample</name>
  </assembly>
  <members>
    <member name="T:AccountExample.Account">
      <summary>
            Represents an account, to which you can deposit and from which you can withdraw money.
            </summary>
      <invariant>_balance >= 0</invariant>
    </member>
    <member name="M:AccountExample.Account.#ctor(System.Single)">
      <summary>
            Initializes a new instance of the <see cref="T:AccountExample.Account" /> class.
            </summary>
      <param name="balanceInitial">The initial balance, which will be set.</param>
      <requires>balanceInitial >= 0</requires>
      <ensures>Balance == balanceInitial</ensures>
    </member>
    <member name="M:AccountExample.Account.Deposit(System.Single)">
      <summary>
            Deposits the specified amount to the account.
            </summary>
      <param name="amount">The amount to deposit.</param>
      <requires>amount > 0</requires>
      <ensures>Balance == (Contract.OldValue(Balance) + amount)</ensures>
    </member>
    <member name="M:AccountExample.Account.Withdraw(System.Single)">
      <summary>
            Withdraws the specified amount from the account.
            </summary>
      <param name="amount">The amount to withdraw.</param>
      <requires>amount > 0</requires>
      <requires>amount <= Balance</requires>
      <ensures>Balance == (Contract.OldValue(Balance) - amount)</ensures>
    </member>
    <member name="P:AccountExample.Account.Balance">
      <summary>
            The current balance of the account.
            </summary>
      <value>The account's balance.</value>
      <setter>
        <requires>value >= 0</requires>
      </setter>
    </member>
  </members>
</doc>

In a second step of the build process, the DocProject generates the documentation for the „AccountExample“ project by taking its XML documentation file. When finished, we’ll have a nice CHM file with the documentation of our example project.

In this documentation we can see our contracts now. On class level, we have our invariant:

Class invariants in Sandcastle documentation

And on method (+properties) level, we get the pre- and postconditions:

Method contracts in Sandcastle documentation

Conclusion

As you can see, contracts in documentation are really valuable. Including them in Sandcastle documentation brings the claim of „checked documentation“ to life! This really helps other developers to understand the intent of your classes by looking at the documentation. And by automatically generating documentation out of your code-based contracts, you can be sure that docu and code do not run out of sync. This really puts more value on Code Contracts and is a real practical advantage!

kick it on DotNetKicks.com

New Code Contracts Release

On September 4th, Microsoft has made a new Code Contracts release available. Release 1.2.20903 (4 Sep 2009) comes among others with the following changes:

  • Inclusion of Code Contracts into Sandcastle documentation! Thereby, Code Contracts achieve a full state of „checked documentation“.
  • Improvements of the dynamic and static checker
  • More contracts on core .NET framework assemblies
  • Silverlight 3 support
  • Many bugfixes on community feedback

Important hint: there are no API changes! Thus existing examples and blog posts on Code Contracts remain valid. Have a look at the release notes for a full list of changes.

Please keep posting your comments and suggestions for improvement on the Code Contracts forum.

Code Contracts #7: Relation to Guard classes

Hey guys. After two months of many things to do I come back again with an article to Code Contracts. This day’s topic are guard classes and how they relate to Code Contracts.

Recently my colleague AJ posted a really nice article about guard classes. He’s the first one who explained the topic as a whole and showed the advantages of using guards. In short version, guard classes in this context are mainly about guarding against passing invalid arguments into class methods.

For example, without having a guard, you would check method arguments that way:

public void FooMethod(string arg)
{
    if(arg == null)
        throw new ArgumentNullException("arg");
    if(arg == "")
        throw new ArgumentOutOfRangeException("arg");
    ...
}

While this approach is defensive and can lead to less errors, it’s quite ugly to have those checks defined in every method directly. First, the if-clauses are polluting the method’s body. The if and throw keywords are too much information at this location. Second, for example if a string should not be empty, it’s obvious that it may not be null as well. And what if we want to log those exceptions or do something else (for example inform an administrator)? Here come guard classes into play. The aspect of throwing exceptions and perhaps do something before that is outsourced into a separate utility class Guard. With that on hand, the example from above would transform into:

public void FooMethod(string arg)
{
    Guard.AssertNotEmpty(arg, "arg");
    ...
}

You can find the guard’s AssertNotEmpty() method in AJ’s post.
The guard encapsulates the argument validation as cross-cutting-concern and makes it exchangable. The call clearly expresses what is done at that point and thus it’s better separated from the core logic of the method. It concentrated on the main purpose and not on the implementation details.

Well, how are method guards fitting with Code Contracts or Design by Contract (DbC) at the whole? The simple answer: method guards are nearly equivalent to preconditions in DbC! They express the basic conditions on level of physical constraints, under which a method is expected to work correctly.

With Code Contracts, in .NET 4.0 we don’t need an explicit Guard class any longer. The above example can be realized with Code Contracts as:

public void FooMethod(string arg)
{
    Contract.Requires(arg != null, "arg should not be null");
    Contract.Requires(arg != "", "arg should not be empty");
    ...
}

As with guard classes, this ‚precondition block‘ abstracts the implementation details of the check itself and it’s purpose is obvious, thus leading to a separation of the core logic, if you look at the method with developer’s eyes.
One ‚problem‘ remains with this example. With the guard class we’ve had the chance to define individual methods, that fit our needs. For example, it checks for empty strings that they aren’t null as well (please take aside String.IsNullOrEmpty() for a moment) or it puts in logging logic. Code Contracts gives us just the Contract.Requires() method, which doesn’t have these abilities at first. If you have many repeating individual checks I suggest to use a separate static class that contains all of your needed checks as methods, that return a boolean value if the check passes. Those methods must be declared [Pure] in order to be used in contracts, thus they must be free of observable side effects. With such a class Check, the example above would look as follows:

public void FooMethod(string arg)
{
    Contract.Requires(Check.NotEmpty(arg), "arg should not be null or empty");
    ...
}

Check is simple in this case:

public static class Check
{
    [Pure]
    public static bool NotEmpty(string arg)
    {
        return ((arg != null) && (arg != ""));
    }
}

Alternatively, you could define extension methods on the datatypes, that should get individual checks. This frees you from a dedicated class, that must know all of the datatypes to check.

For doing additional stuff like logging on fail of a precondition, you get the ability to plug in your own custom contract runtime class. Please read the Code Contracts documentation for detailed information on this subject.

Thus, Code Contracts give you the same advantages as guard classes. But moreover, there are clear additional benefits!
First, you are free to change the check behavior of your preconditions by configuration. The Code Contracts tools allow you to perform checks in debug mode only or even in the release build. Furthermore you can define, if you want the program to Assert or to throw an exception, if a precondition check fails and so on. Thus, you get a high flexibility to adapt Code Contracts to your own needs.
Second, Code Contracts give you the ability to directly extend the interface of your class. It allows you to define contracts on abstract classes and interfaces, that will be automatically taken into concrete implementations.
Third, contracts of all kinds are derived to every subclass of the class, where you have defined them. By that, you aren’t allowed to add any precondition in your subclass with Code Contracts, but you are able to define additional postconditions or invariants. Thereby, the compliance of the Liskov Substitution Principle is enforced on the level of contracts.
Fourth, don’t forget that DbC is a design principle and goes beyond the technical implementation on the level of guard classes.
Fifth, precondition checks allow tool support. They can be included in the run of the static checker and even the automatic test generator Pex is aware of contracts and uses preconditions of your methods as test oracle.

That’s it for now. In conclusion, Code Contracts go beyond guard classes and because they are a core component of .NET 4.0, you don’t need custom guard classes any longer. Simply use contracts instead…

kick it on DotNetKicks.com

Code Contracts #6: Modelling constraints and state

(Note: this article has been updated on 2009/05/16 by replacing the example and adding some more information)

Modelling constraints on class properties and valid state of classes explicitly is an interesting topic and sometimes I catch myself being frustrated by the lack of handling these aspects through current programming languages. With „constraint“ I mean a condition on one class property or on a set, which equals a subset of the properties for the class. The same is true for the „state of a class“. Periodically I run into situations, where I have for example two properties, whose values depend on each other. And what I want is to express explicitly, that when property 1 is in state X, then property 2 must be in state Y and vice versa and that this constraint on those properties (their depending state) mustn’t be broken!

Let’s consider a (very) little example in form of the following class MinMax:

public class MinMax
{
    public int MinValue { get; set; }
    public int MaxValue { get; set; }
}

Not too impressive, isn’t it? 😉 But as you can imagine, there is one obvious constraint: MinValue <= MaxValue. Two other constraints are related to each property for itself – they mustn’t be less than 0: MinValue >= 0 and MaxValue >= 0 must be true. If those 3 conditions are true, then the class can be seen to be in a valid state. And in this case, we want to ensure this valid state all the time. The question follows quickly: How to model these constraints? Normally, you as programmer wouldn’t be very concerned about that. For example, in the setters of MinValue and MaxValue, you would check the constraints and throw an exception, if they don’t hold:

public class MinMax
{
    private int _MinValue;
    public int MinValue {
        get { return _MinValue; }
        set
        {
            if (value %gt; MaxValue)
                throw new ArgumentException("value can't be greater than MaxValue");
            if (value < 0)
                throw new ArgumentException("value can't be less than 0");

            _MinValue = value;
        }
    }

    private int _MaxValue;
    public int MaxValue
    {
        get { return _MaxValue; }
        set
        {
            if (value < MinValue)
                throw new ArgumentException("value can't be less than MaxValue");
            if (value < 0)
                throw new ArgumentException("value can't be less than 0");

            _MaxValue = value;
        }
    }
}

There’s an even better way, when you use a Guard class for that. Better, because you’ve outsourced the exception throw into the guard and you can do additional things there like logging something:

public class MinMax
{
    private int _MinValue;
    public int MinValue
    {
        get { return _MinValue; }
        set
        {
            Guard.Against<ArgumentException>(
                value > MaxValue, "value can't be greater than MaxValue");
            Guard.Against<ArgumentException>(
                value < 0, "value can't be less than 0");

            _MinValue = value;
        }
    }

    private int _MaxValue;
    public int MaxValue
    {
        get { return _MaxValue; }
        set
        {
            Guard.Against<ArgumentException>(
                value < MinValue, "value can't be less than MaxValue");
            Guard.Against<ArgumentException>(
                value < 0, "value can't be less than 0");

            _MaxValue = value;
        }
    }
}

public static class Guard
{
    public static void Against<TException>(bool assertion, string message)
        where TException : Exception
    {
        if (assertion)
            throw (TException)Activator.CreateInstance(typeof(TException), message);
    }
}

So it seems to be pretty easy to handle our constraints, right? Please don’t just take this stupid example into account. Imagine more complex cases, where you have numerous constraints on your class properties (one property or more than one depending properties), which aren’t far so obvious as in this example. Can you imagine the problems which arise, when you model them implicitly?

What if we would have a mechanism to model such (depending) property constraints explicitly, thus expressing valid class states? This would have some interesting advantages. First it helps you as programmer in creating and extending your class by ensuring that the constraints are maintained. Second it works as checked documentation for your code. If other programmers are extending your class, they would be aware of the constraints. By making things explicit and code-checked, it’s ensured that your classes are in valid state at every time by watching the defined constraints. Take MinMax as an example yet again. If you or another programmer is extending the class, you are not forbidden to write _MinValue and _MaxValue directly, thus going around the „state maintainers“ in form of the setters in MinValue and MaxValue and the calls to Guard. This example is small enough to not getting confused, but in more tricky cases the class could be left easily in an inconsistent state and yield more problems. An explicit model could lead a way out of that! Third when you distribute your components to third-party users, you would yet again reveal your intent by making the constraints of the class explicit. Users would be aware of them and could easier reproduce the behavior of your components. Hence there’s a much better chance that they use your class in a proper way from the beginning.

Do we have a mechanism to model such things? First if we think about class state, perhaps the GoF State pattern comes into mind, but that doesn’t fit our needs. It doesn’t have the power to make constraints explicit and model valid class state. But we can use Code Contracts for that! Object invariants (= invariants on classes) are exactly what we need. Object invariants give us the power to model constraints on classes explicitly, check them at compile and/or runtime (using the static or dynamic checker) and moreover allow us to define them on interfaces and abstract classes! Implementing/deriving classes must maintain the defined invariants and are allowed to make them stronger (but not weaker). So how would our MinMax-class look with that? Let’s see:

public class MinMax
{
    public int MinValue { get; set; }
    public int MaxValue { get; set; }

    [ContractInvariantMethod]
    protected void ClassConstraints()
    {
        Contract.Invariant(MinValue >= 0);
        Contract.Invariant(MaxValue >= 0);
        Contract.Invariant(MinValue <= MaxValue);
    }
}

That’s really small and seems to be pretty, doesn’t it? With the ContractInvariantMethod we can declare a method that contains the invariants/constraints of the class, which must be maintained by every class method (including get/set on properties). This method and its checks are run on exit of every other class method. With Contract.Invariant() you’re able to define an invariant. It doesn’t matter if there are simple cases as here or more complex cases on depending properties (for example implications) – every boolean expression can be modelled with that.

However somebody could find some issues with this example, so let’s explain. The above code is pretty, because the constraints are outsourced to one single method (thus avoiding redundancies) and you haven’t to take care of calling this method everytime (because Code Contracts will call it for you on exit of every other method).
As first issue, callers (clients) of the MinValue.set and MaxValue.set methods don’t see directly which values are allowed, because it’s not part of the method contract (the preconditions on the setters). In this example it’s ok, because he can look at the invariants (the contract of the whole class) and see, which values are allowed. So this issue is weak here, but in other method cases you really have to duplicate invariants with preconditions, what is some kind of ugly.
Second, the static checker will not be happy with that code, because it’s aware of that you can provide some invalid value in the setters. That’s an issue of Code Contracts itself and I hope the team will come up with some further development to handle this case automatically. So this issue is weak as well.
The third issue seems to be stronger. If an invariant is broken and hence a ContractException is thrown, the wrong value will remain in the current MinMax instance, if you handle the exception outside with try/catch (MinMax is left in an invalid state). If you don’t use the object anymore, that’s no problem, but else you have no chance to go to the state before the exception was thrown, except you’re handling that on your own in the caller/client. Is this a really good issue? Again, it’s not. This issue goes away, if we look at the purpose and behavior of DbC for this case. In DbC the client is responsible for ensuring preconditions when calling a method and if it comes to properties, he has to respect the invariants, too. If the client breaks a method’s contract, then the method itself is not obligated to ensure defined behavior – it’s simply undefined. And since contracts should be compiled out from the release version (while debugging and testing has been run before), that’s no problem at all. The break of a contract means the presence of a bug. The client should not handle such a case (handle the bug) by catching the exception and then further using the object. The object should be thrown away and the client must take care to call the method in a proper way.
As you can see, there are no definite issues with this example. Fortunately for true, because including preconditions in every setter would have meant to duplicate assertions as preconditions and invariants and this would destroy the advantage of having minimal check redundancies compared with the concept of defensive programming.

This article has shown some interesting aspect of Code Contracts. Modelling constraints (on (depending) properties) and valid class states is not handled very well by programming languages and easily yields to various coding problems, since your intention isn’t made explicit and valid class state isn’t checked automatically. Code Contracts can help us in this case very well by the use of object invariants. One more time making things explicit helps you as programmer and other programmers that use or extend your components.

kick it on DotNetKicks.com