Tuesday, November 4, 2008

Microsoft Code Contracts project site

If you are interested in learning more about the coming Design by Contract stuff in .NET 4.0 here is the link for the Microsoft Code Contracts project site. At the site you can download a MSI containing the documentation as well as a research implementation of the code contracts and some of the VS integration for VS2008. However, it’s under the research license so you won’t be able to use it in a production environment.

Sunday, November 2, 2008

Programming by contract features coming in .NET 4.0!!!

LOS ANGELES - OCTOBER 27:  In this photograph ...

Image by Getty Images via Daylife

It happened! The BCL team proved me wrong (see my two previous posts), and I’m very happy that they did!

So, I’ve been sitting for the last couple of hours watching some of the many interesting PDC2008 sessions online. In particular the day 4 sessions “TL51 Research: Contract Checking and Automated Test Generation with Pex” and “PC49 Microsoft .NET Framework: CLR Futures” were extremely interesting from my perspective. In fact, I’m so excited to write this that I’m almost shaking!

What has gotten me so excited was the announcement that we will finally be able to do programming by contract with the next version of the .NET framework. And it will be integrated into VS2010 so we will see contract violations when compiling. Awesome! For those of you who know about the Spec# project, these new PbC features are the evolution of Spec# into something usable, not just by C# but by all .NET languages.

The TL51 session also talked about another extemely cool project called Pex which is now a Microsoft DevLabs project. The Pex project and the programming by contract features makes up a nice bug killing combo. So if you like bug-free code, like I do, you should pay very close attention to these projects in the future.

Finally I’d like to recommend that you go check out the PDC2008 session list. I’m sure you will find at least 1 or 2  interesting talks in there, though I suspect you will find many more. ;)

Wednesday, October 29, 2008

Extensibility in VS2010, possible opening for Spec# features?

The Microsoft Visual Studio .NET logo.

Image via Wikipedia

So, I’ve been watching the PDC2008 keynote and my heart jumped a bit at 1:32:52 in the keynote, which was Scott Guthries part. He was talking about extensibility in VS2010 and here’s a transcription of what he says in the video.

“Going forward you’re going to see, in VS2010, that we’re gonna be opening up the extensibility all over the place. In particular within the IDE itself as well as within the text editor.

With the next release we’re gonna go a step further, and we will also open up the language services and the compiler infrastructure as well. It’s gonna really, we think, enable some really great code capabilities.

You could interpret the second part of the quote in many ways but it just might be a small opening for making Spec#-like features work without having to make an intrusive change of the entire C# language. Of course this is mere speculation and I havn’t been able to find any further information on these language services and compiler infrastructure extensibility points so time will tell what it really meant. But for now I’ll take it and hold on to it as a bit of hope that we will someday see Spec# fetaures in our day-to-day projects.

Friday, October 24, 2008

How to make a non-nullable type wrapper in C#, today…

The Story of Nothing, in Arizona
Image by cobalt123 via Flickr

I was reading up on the development on Spec# and at the same time trying to figure out if we would start to see Spec# features in C#, anytime soon… Unfortunately, I don’t think we will find any Spec# features in C# 4.0, but I hope the team will prove me wrong.

If you haven’t looked at Spec# yet I strongly encourage you to take a look at it. The short story is that it is a research project which focuses on adding contract oriented constructs to the C# language. You can read more about it at the Spec# homepage or watch the Spec# introduction video on Channel9 which shows off some of the very cool features contract oriented programming brings to the table.

One of the features of Spec# is non-nullable types which is a type wrapper for reference types, sort of like the Nullable<T> type we got in C# 2.0 for value types, but with opposite meaning. In Spec# non-null types can be written as “object!”.

When a type is wrapped with the non-nullable type it can never be set to null. I hope you are now starting to think; “Cool, that would be a nice feature to have in C#”… If you are not, let me explain why you should.

Imagine a world where you could avoid writing code like this:

public void DoStuff(object input)
{
  if (input == null)
    throw new ArgumentNullException("input");

  // Method implementation...
}

Instead you could let the language and the compiler do the null checks for you. If you are a developer by profession, think back on all the applications you’ve made and think of all the null-checking code you’ve written that you could’ve avoided if you had the non-null type feature. Or better yet, think of all the null-checks you forgot to write and you then later discovered when a tester or customer reported an error that turned out to be a null reference exception. Ahh yes, those were the days, right?

Now, since we don’t expect Spec# features in C# anytime soon is there any way we might be able to implement this functionality with what we have? How would we go about writing a non-null type in C#? Well, a good place to start is to fire up reflector and look at how the Nullable<T> type is implemented. After doing that and looking at Jon Skeet’s proposal, I came up with the following slightly modified code:

public struct NonNull<T> where T : class
{
  private readonly T _value;
  public T Value { get { return _value; } }

  public NonNull(T instance)
  {
    if (instance == null)
    throw new ArgumentNullException("instance", "The \"instance\" parameter must not be null.");

    _value = instance;
  }

  public override int GetHashCode()
  {
    return _value.GetHashCode();
  }

  public override bool Equals(object obj)
  {
    return _value.Equals(obj);
  }

  public static bool operator ==(NonNull<T> valueA, NonNull<T> valueB)
  {
    return valueA._value == valueB._value;
  }

  public static bool operator !=(NonNull<T> valueA, NonNull<T> valueB)
  {
    return valueA._value != valueB._value;
  }

  public static implicit operator NonNull<T>(T value)
  {
    return new NonNull<T>(value);
  }

  public static explicit operator T(NonNull<T> value)
  {
    return value._value;
  }
}

But as Jon points out in his excellent blog post that would cause a big problem, since a struct always adds a default parameter-less constructor (that you can’t directly customize) it would be possible to instantiate a NonNull variable with the empty constructor, and thus let the non-null type contain a null value which it clearly shouldn’t. Jon solved this problem by putting a null check in the getter of the “Value” property but this would still hide a potential null reference error till pretty late in a runtime flow. The good news is I found a different solution.

After doing some research I found out that MSIL doesn’t require a default empty constructor to be empty. I then simply compiled a version of the code that had an extra constructor with a dummy parameter and then deleted the parameter from the compiled assembly using the awesome Reflexil plug-in for reflector. And presto, one nice little generic NonNull type wrapper was born. The final code used for this type was:

public struct NonNull<T> where T : class
{
  private readonly T _value;
  public T Value { get { return _value; } }

  [Obsolete("The default parameterless constructor has been disabled please use NonNull<T>(T instance) constructor instead.", true)]
  public NonNull(object dummy)
  {
    throw new NotSupportedException("The default parameterless constructor has been disabled please use NonNull<T>(T instance) constructor instead.");
  }

  public NonNull(T instance)
  {
    if (instance == null)
    throw new ArgumentNullException("instance", "The \"instance\" parameter must not be null.");

    _value = instance;
  }

  public override int GetHashCode()
  {
    return _value.GetHashCode();
  }

  public override bool Equals(object obj)
  {
    return _value.Equals(obj);
  }

  public static bool operator ==(NonNull<T> valueA, NonNull<T> valueB)
  {
    return valueA._value == valueB._value;
  }

  public static bool operator !=(NonNull<T> valueA, NonNull<T> valueB)
  {
    return valueA._value != valueB._value;
  }

  public static implicit operator NonNull<T>(T value)
  {
    return new NonNull<T>(value);
  }

  public static explicit operator T(NonNull<T> value)
  {
    return value._value;
  }
}

As you can see I opted to mark the default constructor as obsolete because that gives a nice little compile-time error if it’s used. I’m also throwing a NotSupportedException from the constructor if it happens to be executed by reflection. I realize that this class isn’t as user-friendly as you would like it to be, but for now it’s probably the closest we’ll get without help from the C# language team.

If you would like to try it out you can get a precompiled NonNull type here. Enjoy!

Wednesday, August 27, 2008

Extension Types for easier (and strongly typed) Attribute checks

I just saw a blog post from Alex Mueller about marker interfaces and C# attributes and which way you should be using them.

I, for one, believe that attributes are far the best way to mark a class instead of using an empty marker interface. Why? Well, there are several good reasons to use attributes over interfaces, especially when it comes to inheritance. That aside, attributes are also a lot more flexible than interfaces.

So why don’t people use attributes more often? The most common complaint is that interfaces are easier to use and check for in code (I.e. interfaces requires less code). But I think this is mainly because people don’t know where to look for help in the framework. So I’ve devised 30 extension methods that will make your work with attributes a little bit easier and strongly typed.

public static class AttributeExtensions
{
  // Attribute.IsDefined shortcuts
  public static bool HasAttribute<T>(this object element) where T : Attribute
    { return Attribute.IsDefined(element.GetType(), typeof(T)); }
  public static bool HasAttribute<T>(this object element, bool inherit) where T : Attribute
    { return Attribute.IsDefined(element.GetType(), typeof(T), inherit); }
  public static bool HasAttribute<T>(this Assembly element) where T : Attribute
    { return Attribute.IsDefined(element, typeof(T)); }
  public static bool HasAttribute<T>(this Assembly element, bool inherit) where T : Attribute
    { return Attribute.IsDefined(element, typeof(T), inherit); }
  public static bool HasAttribute<T>(this MemberInfo element) where T : Attribute
    { return Attribute.IsDefined(element, typeof(T)); }
  public static bool HasAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute
    { return Attribute.IsDefined(element, typeof(T), inherit); }
  public static bool HasAttribute<T>(this Module element) where T : Attribute
    { return Attribute.IsDefined(element, typeof(T)); }
  public static bool HasAttribute<T>(this Module element, bool inherit) where T : Attribute
    { return Attribute.IsDefined(element, typeof(T), inherit); }
  public static bool HasAttribute<T>(this ParameterInfo element) where T : Attribute
    { return Attribute.IsDefined(element, typeof(T)); }
  public static bool HasAttribute<T>(this ParameterInfo element, bool inherit) where T : Attribute
    { return Attribute.IsDefined(element, typeof(T), inherit); }

  // Attribute.GetCustomAttribute shotcuts
  public static T GetAttribute<T>(this object element) where T : Attribute
    { return Attribute.GetCustomAttribute(element.GetType(), typeof(T)) as T; }
  public static T GetAttribute<T>(this object element, bool inherit) where T : Attribute
    { return Attribute.GetCustomAttribute(element.GetType(), typeof(T), inherit) as T; }
  public static T GetAttribute<T>(this Assembly element) where T : Attribute
    { return Attribute.GetCustomAttribute(element, typeof(T)) as T; }
  public static T GetAttribute<T>(this Assembly element, bool inherit) where T : Attribute
    { return Attribute.GetCustomAttribute(element, typeof(T), inherit) as T; }
  public static T GetAttribute<T>(this MemberInfo element) where T : Attribute
    { return Attribute.GetCustomAttribute(element, typeof(T)) as T; }
  public static T GetAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute
    { return Attribute.GetCustomAttribute(element, typeof(T), inherit) as T; }
  public static T GetAttribute<T>(this Module element) where T : Attribute
    { return Attribute.GetCustomAttribute(element, typeof(T)) as T; }
  public static T GetAttribute<T>(this Module element, bool inherit) where T : Attribute
    { return Attribute.GetCustomAttribute(element, typeof(T), inherit) as T; }
  public static T GetAttribute<T>(this ParameterInfo element) where T : Attribute
    { return Attribute.GetCustomAttribute(element, typeof(T)) as T; }
  public static T GetAttribute<T>(this ParameterInfo element, bool inherit) where T : Attribute
    { return Attribute.GetCustomAttribute(element, typeof(T), inherit) as T; }

  // Attribute.GetCustomAttributes shortcuts
  public static T[] GetAttributes<T>(this object element) where T : Attribute
    { return Attribute.GetCustomAttributes(element.GetType(), typeof(T)) as T[]; }
  public static T[] GetAttributes<T>(this object element, bool inherit) where T : Attribute
    { return Attribute.GetCustomAttributes(element.GetType(), typeof(T), inherit) as T[]; }
  public static T[] GetAttributes<T>(this Assembly element) where T : Attribute
    { return Attribute.GetCustomAttributes(element, typeof(T)) as T[]; }
  public static T[] GetAttributes<T>(this Assembly element, bool inherit) where T : Attribute
    { return Attribute.GetCustomAttributes(element, typeof(T), inherit) as T[]; }
  public static T[] GetAttributes<T>(this MemberInfo element) where T : Attribute
    { return Attribute.GetCustomAttributes(element, typeof(T)) as T[]; }
  public static T[] GetAttributes<T>(this MemberInfo element, bool inherit) where T : Attribute
    { return Attribute.GetCustomAttributes(element, typeof(T), inherit) as T[]; }
  public static T[] GetAttributes<T>(this Module element) where T : Attribute
    { return Attribute.GetCustomAttributes(element, typeof(T)) as T[]; }
  public static T[] GetAttributes<T>(this Module element, bool inherit) where T : Attribute
    { return Attribute.GetCustomAttributes(element, typeof(T), inherit) as T[]; }
  public static T[] GetAttributes<T>(this ParameterInfo element) where T : Attribute
    { return Attribute.GetCustomAttributes(element, typeof(T)) as T[]; }
  public static T[] GetAttributes<T>(this ParameterInfo element, bool inherit) where T : Attribute
    { return Attribute.GetCustomAttributes(element, typeof(T), inherit) as T[]; }
}


Now you can check for the existence of an attribute like this:
 
var instance = new SomeClass();

// How to check for attributes using the extension methods.
bool hasMarkerAttribute = instance.HasAttribute<MyMarkerAttribute>();

// How to check for marker interface using unfair compiler sugar. ;)
bool hasMarkerInterface = instance is IMyMarkerInterface; // Not that much shorter, right?


Well, I hope someone can use this… Any thoughts or criticisms for the code will be greatly appreciated. Otherwise, enjoy! ;)