Contractual Obligations

Last night Wednesday 2nd of December I attended a presentation at the Melbourne Patterns & Practices User Group. After the Gang of Four pattern discussion (which was Chain of Responsibility) was a presentation on .NET Code Contracts.

Code Contracts are a Microsoft Labs Research project, that now has a beta release.

Code Contracts provide a language-agnostic way to express coding assumptions in .NET programs. The contracts take the form of preconditions, postconditions, and object invariants.

At their simplest level of application in a code base Code Contracts will help group guard conditions for functions, and also easily support exit guard conditions when a public method completes.

public List<Markers> ExtractGeneticMarkers(List<BioSample> samples)
   //Pre conditions use: 
   Contract.Requires(samples != null);
   //a lambda expression to perform the contract check on all elements
   Contract.Requires(samples.All(s => s.geneticData != null));

   //Post conditions use:
   Contract.Ensures(Contract.Result<Markers>() != null)

  var markers = new List<Makers>(); 
  //function logic
  return makers;

A summary of some of the benefits:

  • Compile time contract validation and error(/warning) output.
  • Runtime contract validation and exceptions thrown.
  • Toggling the contracts per assembly [Full / Pre & Post / Pre / ReleaseRequires / None].
  • Inheritance of contracts, even from interfaces.
  • Outputting documentation from the contracts, for accurate reflection of the state of the code.

It’s quite an extensive discussion for all it’s potential applications and what can be achieved, so for More Info check out some other posts on the topic too:

Published by Nick Josevski

Software Engineer at Octopus Deploy

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: