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 #1: Basic information

During the last days and weeks, I’ve had the chance to make my mind up on Code Contracts, validation vs. verification of code and code quality on the whole. I’ve made some examples with Code Contracts and want to start a basic blog post series here, which should give you some further information on this. Code Contracts as project are not baked, yet. Thus I don’t throw with mud about things, that will definitely work in the future. This makes no sense! I just want to share some knowledge and want to know what you think about this altogether.

„Code Contracts“ is a project from the Microsoft DevLabs (http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx) and can be downloaded and installed in a very early state at the moment. The origin of Code Contracts is the programming language Spec#, which is extending C# at aspects for definition of conditions, that have to be fulfilled by part of a programmer’s code (classes, methods, variables, …). Moreover, the „Code Contracts Library“ has been decoupled from Spec# for Code Contracts and has been modified to work with the .NET framework in general. Thus, Spec# as research project has served its time, but it’s living on with Code Contracts. The impact of Code Contracts is not to underestimate: the component is going to be an element of the .NET 4.0 class library and thus it’s making its way into all .NET based languages.

But what’s hiding behind Code Contracts? The idea is the same as in Spec#: taking your code under contract, that means setting conditions on it. The programmer then has to take care about fulfilling those conditions (contracts) with his code. This idea isn’t new at all, since it comes originally from the Eiffel programming language, which has been introduced in 1985 already. Therefore Eiffel supports the Design by Contract (DbC) principle, whereby the following aspects can be defined in the code:

  • pre-conditions: Those are declared on method level and define conditions, which have to be fulfilled at entrance of a method (that means which contracts have to be kept by the caller). Mainly, these are conditions on method parameters (e.g. prohibition of null-values).
  • post-conditions: Those are declared on method level, too and define conditions, that have to be fulfilled at exit of a method (meaning contracts, that the method’s code has to ensure). For example, one could make conditions on the return value, that callers of the method could rely on.
  • invariants: Those are definitions on class level, depicting conditions, that have to be fulfilled at exit of any method of the class. For example, one could define conditions on the value of fields or properties of the class (be not null, be positive, have a defined value range, etc.).

The following example of a method deposit for a banking account illustrates the use of pre- and post-conditions in their original language Eiffel:

deposit (amount: INTEGER) is
    require
        non_negative: amount > 0
    do
        balance := balance + amount
    ensure
        updated: balance = old balance + amount
end

Pre-conditions can be defined with require, ensure defines post-conditions, that have to be true at exit of the method. Those can also describe the value of class members as shown in this (trivial) example for the member balance. Thereby, Eiffel is checking at runtime if the contracts are fulfilled and if not it’s notifying with an error.

Just those definitions are possible with Code Contracts in .NET, too. With static methods on the newly introduced class Contracts, the programmer gets the possibility to define such contracts. The deposit method from the example above would look in .NET Code Contracts as follows:

public void Deposit(int amount)
{
    Contract.Requires(amount > 0);
    Contract.Ensures(Balance == Contract.OldValue(Balance) + amount);

    Balance += amount;
}

With Contract.Requires() one can define pre-conditions, with Contract.Ensures() post-conditions. Contract.OldValue() can be used in a post-condition and is a placeholder for the value of a variable on class level (property, field) at entrance of the method.

To use Code Contracts in your own projects and get first insights, you have to download the current package from http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx and install it. Then, if you add a reference to the Microsoft.Contracts.dll to your project, you can access the Contract class from the namespace System.Diagnostics.Contracts. But again as reminder: the Code Contracts project is in an early state at the moment, so don’t expect a perfect solution. The team is working hard to improve their code and thus everybody should appreciate their work. Many things have to be done until the rise of .NET 4.0, but I’m sure that they’ll do their job very well.

Those are first basic information about Code Contracts. Next blog posts will involve deeper knowledge about Code Contracts, the components of Code Contracts, more examples and information about why it makes a change and why one should care about.

kick it on DotNetKicks.com