Derik Whittaker

Syndication

News


Code Contracts Primer – Part 6 Interface Contracts

*** NOTE *** This post has been a long time coming, I would like to thank Kevin Hazzard for doing a kick ass Contracts session at TriNug and reminding me to get off my ass and blog about this great feature *** NOTE *** 

If you are not familiar with the Code Contracts library which is coming out of Microsoft R&D labs, you need to check this pretty cool little library out.  As of Vs2010/.Net 4.0 this library will be making the jump out of the R&D labs. 

Over the next few blog posts we will be taking a look at the topics below.

What is a Interface Contract?

This part of the contracts library allows you to provide a ‘buddy class’ (as Kevin called it) which tags along with some interface in your application and provides contract validation for your interface.  Below is the definition per the contracts user guide:

Since most languages/compilers (including C# and VB) will not let you put method bodies within an interface, writing contracts for interface methods requires creating a separate contract class to hold them. The interface and its contract class are linked via a pair of attributes.

Imagine you have the following interface as defined below

With this interface assume you have the following 2 implementation classes, each which utilized various contracts to ensure quality.

One thing should immediately jump out at you from looking at the above implementation classes, we have redundant logic in each of our classes.  This is where the beauty of Interface Contracts come into play.  I am able to create a stand alone class which can hold onto my duplicated contracts logic and use this class for validation. To do this I need to create the class below;

When looking at the class above there are a few things that need to be pointed out

  1. There is no need to provide a ‘real return’ value if you have a non-void method.  You simply can return some default value.  The reason for this is that the IL re-writer is not going to keep your code as is, so no need to provide anything.
  2. You will want to explicitly reference your interface methods (ie IPayrollCalcualtor.CalculatePaycheck) and leave the methods private.  If you do not do this you will not get the behavior you expect.
  3. You need to decorate your class with the ContractClassFor attribute and this MUST point to the interface class which the contract applies to.

Now that we have defined our ‘buddy class’ which holds onto our interface contracts we need to modify our original interface in order to link it to the contract implementation.  To do this take a look at the modified interface below:

Notice the only difference in the code above from the original code is the introduction of the ContractClass attribute.  This attribute creates a circular dependency to the implementation class for the contracts.  If you do not have this setup your contracts will not work as expected.

Now that I have setup my interface contract I can remove the redundant contracts from my 2 classes, the code below shows this in action.

As you can see Interface Contracts can allow for reduced redundancy and increased clarity.  Hope this helps.

Till next time,


Posted 05-14-2010 5:41 AM by Derik Whittaker

[Advertisement]

Comments

Mike Thomas wrote re: Code Contracts Primer – Part 6 Interface Contracts
on 05-14-2010 2:35 PM

I agree, it was a great presentation at TriNUG. Thanks Derik for another blog posting on the topic! I will be reading your blog series on Contracts today.

I loaded contracts in my VS2010 and got a Project load failure. Fixed simply by rebooting W7 x64. Details at:

http://bit.ly/a8kaxS

Adding a reference to Microsoft.Contracts and I'm off and running. First project Validated 100%  :-)

Mike Thomas wrote re: Code Contracts Primer – Part 6 Interface Contracts
on 05-14-2010 3:09 PM

Great posts Derik.

Glad I read your series, too! I need to check out debug stepping like you mentioned in Part 5, on the final release of VS2010 and latest version of Contracts.

Mike

jdn wrote re: Code Contracts Primer – Part 6 Interface Contracts
on 05-14-2010 7:12 PM

I'm glad you came back to this.  I didn't know you could do this, so very cool.

Mohammad Haroon wrote re: Code Contracts Primer – Part 6 Interface Contracts
on 05-17-2010 3:16 AM

Thanks for the post, it's very useful. But the first question that came into my mind after reading it was:

What's the difference between this and inheritance?

If I'm only going to use contracts with a single interface (in a class that implements many), then does it make any difference?

Andy wrote re: Code Contracts Primer – Part 6 Interface Contracts
on 05-17-2010 4:31 AM

Very clever stuff, but my concern with some of these frameworks (esp this post and particularly the object invariants post) is that we run the risk of creating code that is more difficult to see what's going on, especially when you throw Code Weaving into the mix.

Don't get me wrong - I'm all for making a dev's job easier but I prefer to create readable code, at the expense of a few extra keystrokes.

Call me "old school" but I find the if..then..throw approach far more readable and intuitive and haven't been swayed towards CCs (yet).

Derik Whittaker wrote re: Code Contracts Primer – Part 6 Interface Contracts
on 05-17-2010 4:45 AM

@Mohammad,

The simple answer is that .net does not allow for multiple inheritance at the class level, but does allow for multiple inheritance at the interface level.

By putting these on the interface you can have a concrete class implemented 2+ interfaces each w/ their own set of contracts.

Mohammad Haroon wrote re: Code Contracts Primer – Part 6 Interface Contracts
on 05-17-2010 5:59 AM

@Derik,

Thanks for your prompt response. Yeah, for cases where you'll need to do this for multiple interfaces, this sounds like a new cool addition. However, the case I was referring to was when you have single class.

I mean, if this new practice performs better (from performance/compilation...etc point of view), then I should stop using the regular inheritance. Should I?

jdn wrote re: Code Contracts Primer – Part 6 Interface Contracts
on 05-19-2010 8:03 PM

@Andy:

I think that's a legitimate concern, and the true answer, as always, is "It depends" but I think, to be honest, you get more comfortable with it over time.

Assuming you are a .NET/Java developer, think about Garbage Collection.  My grandad used to tell me that C and C++ developers had to really worry about that sort of thing.  Obviously, you can still screw up memory management in .NET, but for the most part, especially if you use the using statement, all that magical dispose stuff is taken care of.

CC's are, to me, similar.  Used properly, you don't have to worry about, e.g., null reference exceptions and the like

name wrote re: Code Contracts Primer – Part 6 Interface Contracts
on 06-13-2010 1:52 AM

9  

name wrote re: Code Contracts Primer – Part 6 Interface Contracts
on 06-13-2010 1:52 AM

2  

ñàéò ñåêñ çíàêîìñòâ wrote re: Code Contracts Primer – Part 6 Interface Contracts
on 06-13-2010 6:38 AM

Hey!  www.istu.edu/.../704.page çíàêîìñòâà äëÿ ñåêñà

çíàêîìñòâà äëÿ ñåêñà wrote re: Code Contracts Primer – Part 6 Interface Contracts
on 06-14-2010 5:37 AM

hi! www.istu.edu/.../704.page èíòèì çíàêîìñòâà

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)