Using Contracts to discover Liskov Substitution Principle Violations in C#

In his book Agile Principles, Patterns, and Practices in C#, Bob Martin talks about using pre- and post-conditions in Eiffel to detect Liskov Substitution Principle violations. At the time he wrote that C# did not have an equivalent feature and he suggested ensuring that unit test coverage was used to ensure the same result. However, that does not ensure that checking for LSP violations are applied consistently. It is up to the developer writing the tests to ensure that they are and that any new derived classes get tested correctly. Contracts, these days, can be applied to the base class and they will automatically be applied to any derived class that is created.

Getting started with Contracts

If you’ve already got Visual Studio set up to check contracts in code then you can skip this section. If you don’t then read on.

1. Install the Code Contracts for .NET extension into Visual Studio.

2. Open Visual Studio and load the solution containing the projects you want to apply contracts to.

3. Open the properties for the project and you’ll see a new tab in the project properties window called “Code Contracts”

4. Make sure that the “Perform Runtime Contract Checking” and “Perform Static Contract Checking” boxes are checked. For the moment the other options can be left at their default values. Only apply these to the debug build. It will slow down the application while it is running as each time a method with contract conditions is called it will be performing runtime checks.

Visual Studio Project Properties

You are now ready to see code contract issues in Visual Studio.

For more information on code contracts head over to Microsoft Research’s page on Contracts.

Setting up the Contract

Using the Rectangle/Square example from Bob Martin’s book Agile Principles, Patterns and Practices in C# here is the code with contracts added:

public class Rectangle
{
    private int _width;
    private int _height;
    public virtual int Width
    {
        get { return _width; }
        set
        {
            Contract.Requires(value >= 0);
            Contract.Ensures(Width == value);
            Contract.Ensures(Height == Contract.OldValue(Height));
            _width = value;
        }
    }

    public virtual int Height
    {
        get { return _height; }
        set
        {
            Contract.Requires(value >= 0);
            Contract.Ensures(Height == value);
            Contract.Ensures(Width == Contract.OldValue(Width));
            _height = value;
        }
    }
    public int Area { get { return Width * Height; } }
}

public class Square : Rectangle
{
    public override int Width
    {
        get { return base.Width; }
        set
        {
            base.Width = value;
            base.Height = value;
        }
    }

    public override int Height
    {
        get { return base.Height; }
        set
        {
            base.Height = value;
            base.Width = value;
        }
    }
}

The Square class is in violation of the LSP because it changes the behaviour of the Width and Height setters. To any user of Rectangle that doesn’t know about squares it is quite understandable that they’d assume that setting the Height left the Width alone and vice versa. So if they were given a square and they attempted to set the width and height to different values then they’d get a result from Area that was inconsistent with their expectation and if they set Height then queried Width they may be somewhat surprised at the result.

But there are now contracts in place on the Rectangle class and as such they are enforced on Square as well. “Contracts are inherited along the same subtyping relation that the type system enforces.” (from he Code Contracts User Manual). This means that any class that has contracts will have those contracts enforced in any derived class as well.

While some contracts can be detected at compile time, others will still need to be activated through a unit test or will be detected at runtime. Be aware, if you’ve never used contracts before that the contract analysis can appear in the error and output windows a few seconds after the compiler has completed.

Consider this test:

[Test]
public void TestSquare()
{
    var r = new Square();
    r.Width = 10;

    Assert.AreEqual(10, r.Height);
}

When the test runner gets to this test it will fail. Not because the underlying code is wrong (it will set Height to be equal to Width), but because the method violates the constraints of the base class.

The contract says that when the base class changes the Width the Height remains the same and vice versa.

So, despite the fact that the unit tests were not explicitly testing for an LSP violation in Square, the contract system sprung up and highlighted the issue causing the test to fail.

 

Tip of the Day: Getting TFS to remember you each time you open Visual Studio

Because the TFS Server where I work is not on the domain, it will prompt you for credentials each time you log in (unless you’ve previously used the web access and checked the “Remember Me” option). If you don’t want to use the web access portal, you can still get TFS to remember your credentials and not ask you each time you log in.

Go in to the control panel and select “User Accounts”

In the next screen click “Manage Windows Credentials”

In the next screen click “Add Windows Credential”

Then type your details into the form, and press “OK”

You’ll see your new set of credentials appear in the Credential Manager page:

Now when you open up Visual Studio it won’t prompt you for your credentials all the time.

Updated chart of .NET version numbers

Way back when, I published a table detailing the version numbers of the various parts that make up a .NET application: The Tools, the C# language, the Framework itself and the Engine (CLR) that it all runs on. With the latest version about to be released I thought it was time to update that table.

 

Year 2002 2003 2005 2006 2007 2010
Tool VS.NET 2002 VS.NET 2003 VS 2005 VS 2005
+ Extension
VS 2008 VS 2010
Language (C#) v1.0 v1.1 v2.0 v2.0 v3.0 v4.0
Framework v1.0 v1.1 v2.0 v3.0 v3.5 v4.0
Engine (CLR) v1.0 v1.1 v2.0 v2.0 v2.0 v4.0

 

The main new thing is that finally someone has had the good sense to re-sync the version numbers. It all got a bit silly with the release of Visual Studio 2008.

Cool switch snippet

I was watching one of the MSDN Screencasts today and Mike Taulty put in a switch statement that pre-populated itself with valid values for each of the case statements within the switch. I hadn’t seen this before so I investigated further (in other words, I emailed Mike and asked him what he did). It turns out this is a feature that has been in since Visual Studio 2005 and I’d only just noticed.

Essentially, if you are switching on an enumerator the snippet will expand with all the case statements created for you as you can see by the animation below. To access this, follow these steps

  • Type “switch”, the intellisense will show the word “switch” with the torn document icon, indicating it is a snippet.
  • Press the tab key twice to expand the snippet, this will also highlight the text “switch_on”.
  • Change the “switch_on” text to the name of the variable on which you want to switch.
  • Press return twice, this will further expand the switch statement filling in all the cases from the enumerator.

For an example, see the animation below:

switch snippet

Technorati Tags: ,,

 

 

Always show the solution, Dammit!!!

This has got to be the most pointless setting in Visual Studio. I can’t imagine why any reasonable person would want to hide the solution. Maybe it is for those “Morts” I keep hearing about who bundle everything into one giant ball of mud project so have no need to know about mundane things such as solutions.

Always Show Solution

I suppose what gets me most is that I like my right-click. I like to right-click on things and get context sensitive menus. I also normally create a new blank solution then add projects to it. The solution disappear when the number of projects equals one. When there are zero projects the solution shows, but as soon as I add one it disappears so I can’t right-click and add another until I sort this setting out. It was the same in Visual Studio 2005, I was hopping they might have changed the default for VS2008, but no – the mob rule of the Morts wins.

Yes, I realise that I can go to the file menu to add a new project from there, but if I’m already focused in the solution explorer, I want to stay there. I don’t want to make giant leaps across the screen to do these things. I want everything I need within easy reach.

Contradictory messages

While attempting to create a database project in Visual Studio 2008 against a SQL Server 2008 database I got a rather odd error message. The dialog used to create the project requests information about the SQL Server database. It clearly states “The server version must be 2005 or later”. No problem, I thought. So I put in the information about my SQL Server and database in the dialog and tested the connection. So far so good. But as soon as I hit the “Okay” button I got a new message. Apparently, “Only servers up to Microsoft SQL Server 2005 are supported.”

Contradictions

Object Initialisers II

Following on from Gary Short‘s message from my previous post on Object Initialisers, I decided to take a screenshot of Orcas displaying the tooltips.

Screenshot of intellisense showing object initialisers in Orcas

I really have to compliment those that designed and wrote intellisense. Not only does it work with object initialisers, but it is intelligent enough to remove properties that have already be used.

NOTE: This post was rescued from the Google Cache. The original date was Sunday, 11th March 2007.

A start on LINQ

I was at the Microsoft MSDN Roadshow today and I got to see some of the latest technologies being demonstrated for the first time and I’m impressed.

Daniel Moth’s presentation on the Language Enhancements and LINQ was exceptional – It really made me want to be able to use that technology now.

What was interesting was that the new enhancements don’t require a new version of the CLR to be installed. It still uses the Version 2.0 CLR. It works by adding additional stuff to the .NET Framework (this is .NET Framework 3.5) and through a new compiler (the C# 3.0 compiler). The C# 3.0 compiler produces IL that runs against CLR 2.0. In essence, the new language enhancements are compiler tricks, which is why the CLR doesn’t need to be upgraded. Confused yet?

Now that the version numbers of the various components are diverging it is going to make things slightly more complex. So here is a handy cheat sheet:

2002 2003 2005 2006 2007ish
Tool VS.NET 2002 VS.NET 2003 VS 2005 VS 2005
+ Extension
“Orcas”
Language (C#) v1.0 v1.1 v2.0 v2.0 v3.0
Framework v1.0 v1.1 v2.0 v3.0 v3.5
Engine (CLR) v1.0 v1.1 v2.0 v2.0 v2.0

The rest of Daniel’s talk was incredibly densely packed with information. Suffice to say, at the moment, LINQ is going to provide some excellent and powerful features, however, it will also make it very easy to produce code that is very inefficient if wielded without understanding the consequences. The same can be said of just about any language construct, but LINQ does do a remarkable amount in the background.

After the session I was speaking with Daniel and we discussed the power of the feature and he said that, since C#3.0 produces IL2.0 it is possible to use existing tools, such as Lutz Roeder’s Reflector, to see exactly what is happening under the hood. An examination of that will yield a better understanding of how LINQ code is compiler.

LINQ code looks similar to SQL. For example:

var result =
    from p in Process.GetProcesses()
    where p.Threads.Count > 6
    orderby p.ProcessName descending
    select p

This allows the developer to write set based operations in C# a lot more easily than before. A rough equivalent in C# 2.0 to do the same thing would probably look something like this:

List<Process> result = new List<Process>();
foreach(Process p in Process.GetProcesses)
{
    if (p.Threads.Count > 6)
        result.Add(p);
}
result.Sort(new DescendingProcessNameComparer());

* NOTE: Assumes that DescendingProcessNameComparer is an existing comparer that compares two Process objects by their name in descending order.

C# 3.0 introduces the var keyword. This is unlike var in javascript or VB. It is not a variant type. It is strongly typed and the compiler will complain if it is used incorrectly. For example:

var i = 5;
i = "five"; // This will produce a compiler error because i is an integer

In short this was only a fraction of what I learned from just one session – I’ll continue the update as I can.

Tags:

NOTE: This post was rescued from the Google Cache. The original date was Monday, 5th March 2007.


Original comments:

Glad you enjoyed it Colin :-)

Be sure to check out the written version of my talk on my blog!

3/6/2007 11:34 AM | Daniel Moth

Automatic Properties

Continuing my look at the new features found in the C# 3.0 compiler I will look at Automatic Properties.

public class Employee{    public string FirstName { get; set; }
    public string Surname { get; set; }
    public DateTime DateOfBirth { get; set; }
    public Employee Manager { get; set; }}

At first look this might seem more like a definition for an interface, but for the class keyword and the member visibility modifiers.

However, this is actually a new feature where by the compiler will automatically fill in the member fields. This is useful for situations where nothing needs to be done when getting or setting values from the member fields. It means they can be constructed much more quickly as there is no need for tedious creating of private member fields then the public properties. All that is needed is one simple construct.

It is also possible to reduce the visibility of the getter and setter independently. For example, in the above example you may wish to make DateOfBirth to be effectively read-only for all by the class that owns it. You can prefix the set keyword with the private visibility modifier.

But what is the compiler actually producing? The following is the output from Lutz Roeder’s Reflector for the DateOfBirth property:

[CompilerGenerated]
private DateTime <>k__AutomaticallyGeneratedPropertyField2;

public DateTime DateOfBirth
{
    [CompilerGenerated]
    get
    {
        return this.<>k__AutomaticallyGeneratedPropertyField2;
    }
    private [CompilerGenerated]
    set
    {
        this.<>k__AutomaticallyGeneratedPropertyField2 = value;
    }
}

In the code, only the  property is accessible. Attempting to use the compiler generated name produces a compiler error.

If the full name (as shown above) is used then the compiler will complain with three errors:

Compiler errors
# Error File Row Col Project
1 Identifier expected ConsoleApplication2Employee.cs 20 18 ConsoleApplication2
2 Invalid expression term ‘>’ ConsoleApplication2Employee.cs 20 19 ConsoleApplication2
3 ; expected ConsoleApplication2Employee.cs 20 20 ConsoleApplication2

If the <> are removed the message changes to

Compiler errors
# Error File Row Col Project
1 ‘ConsoleApplication2.Employee’ does not contain a definition for ‘k__AutomaticallyGeneratedPropertyField2′ and no extension method ‘k__AutomaticallyGeneratedPropertyField2′ accepting a first argument of type ‘ConsoleApplication2.Employee’ could be found (are you missing a using directive or an assembly reference?) ConsoleApplication2Employee.cs 20 18 ConsoleApplication2

So, why go to all this trouble? Surely it isn’t just to save a few key strokes?

Part of the answer can be seen in a post I made in November 2005: Why make fields in a class private, why not just make them public? and there was a follow up in June 2006 when I returned to The Public Fields Debate Again.

In short, public fields and public properties, although they appear to look identical to the outside in C# are sytactically different once compiled. Automatic Properties are a way to address that. If you, at some point in the future, decide that you need the property to do more then the external interface of the object won’t change, you just turn the automatic property into a normal property/field combination again.

NOTE: This post was rescued from the Google Cache. The original date was Tuesday, 13th March, 2007.

Extensions Methods

I’ve been looking at more of the language enhancements in C# 3.0. In this post I’m going to look at Extensions.

There have been many times went a class has needed to be extended, but the additional code just doesn’t sit right on the class itself. In that case a utility or helper class is created to help carry out these mundane tasks without impacting the main class the helper operates on. It may be because the method requires access to classes that would tightly couple the main class to others.

It is important to remember that the extension method, like any method on a helper or utility class, cannot access the private or protected members of the class it is helping.

For example, take the children’s game Fizz-Buzz which seems to be undergoing a resurgence at the moment. The rules for the method are simple. The program counts from 1 to 100 replacing any value that is divisible by 3 with Fizz and any value that is divisible by 5 with Buzz. If a value happens to be divisible by both 3 and 5 then the output is FizzBuzz. For any other value the number is output.

First here is the version without the extensions:

public static class FizzBuzzHelper
{
    public static string FizzBuzz(int number)
    {
        if ((number % 5) == 0)
        {
            if ((number % 3) == 0)
                return "FizzBuzz";
            return "Buzz";
        }
        if ((number % 3) == 0)
        {
            return "Fizz";
        }
        return number.ToString();
    }
}

class Program
{
    static void Main(string[] args)
    {
        for (int i = 1; i <= 100; i++)
        {
            Console.WriteLine(FizzBuzzHelper.FizzBuzz(i));
        }
        Console.ReadLine();
    }
}

And now the version with the extensions:

public static class FizzBuzzHelper
{
    public static string FizzBuzz(this int number)
    {
        if ((number % 5) == 0)
        {
            if ((number % 3) == 0)
                return "FizzBuzz";
            return "Buzz";
        }
        if ((number % 3) == 0)
        {
            return "Fizz";
        }
        return number.ToString();
    }
}

class Program
{
    static void Main(string[] args)
    {
        for (int i = 1; i <= 100; i++)
        {
            Console.WriteLine(i.FizzBuzz());
        }
        Console.ReadLine();
    }
}

There aren’t actually that many changes (and the example is somewhat trivial).

First, in the extension method, the this keyword is placed before the parameter. It indicates that the extension will go on the int (or rather the Int32) class.

Second, when the extension method is called there is no reference to the utility class. It is simply called as it it were a method on the class (in this case Int32). Also, note that the parameter is not needed because it is implied by the object on which the extension method is applied.

Lutz Roeder’s reflector is already conversant with extension methods so the compiler trickery cannot be seen in the C# view of the method. However, the IL reveals that deep down it is just making the call as before. The following is the extension version:

L_0007: call string ConsoleApplication3.FizzBuzzHelper::FizzBuzz(int32)
L_000c: call void [mscorlib]System.Console::WriteLine(string)

And this is the old-style helper method call:

L_0007: call string ConsoleApplication3.FizzBuzzHelper::FizzBuzz(int32)
L_000c: call void [mscorlib]System.Console::WriteLine(string)

They are identical. So, how does the compiler tell what it needs to be doing?

The method header for the regular helper method:

.method public hidebysig static string FizzBuzz(int32 number) cil managed
{

The method header for the extension method:

.method public hidebysig static string FizzBuzz(int32 number) cil managed { .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor()

And that’s it. C# just hides the need for the ExtensionAttribute. In VB the attribute needs to be explicitly declared on the method.

Intellisense also helps out with extensions. Each extension method appears in the intellisense on the object it is extending. To ensure that the developer is aware that it is an extension the icon in the list has a blue arrow and the tool tip is prefixed with “(extension)”

orcas-extensions-intellisense

It is also possible to create extension methods that take more than one parameter. For example:

public static class PasswordHashHelper
{
    public static byte[] HashPassword(this string password, byte[] salt)
    {
        // Implementation here
    }
}

It is important to note that the this modifier can only be placed on the first parameter. To do otherwise would generate the compiler error “Method ‘{method name}’ has a parameter modifier ‘this’ which is not on the first parameter”

The above multi parameter extension method can then be used like this:

byte[] hashedPassword = plainTextPassword.HashPassword(salt);

NOTE: This entry was rescued from the Google Cache. The original date was Thursday, 15th March, 2007.

Follow

Get every new post delivered to your Inbox.

Join 25 other followers