better contracts better code - august 2010

Post on 28-Jun-2015

783 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Better Contracts. Better Code.

An Introduction to Microsoft Code Contracts in the .NET 4.0 Framework

August 2010W. Kevin Hazzard, C# MVP

What is code?

PromiseGuaranteeObligation

IntentAssumptionBinding

http://www.asu.edu/clas/shs/aald/

A Simple Illustration

public int[] ApplyDiscounts(int maxPercentageAllowed,Customer[] customers,Promotion[][] promotions )

{// apply the promotions here// and return the results

}

C# Does OK with Types & Structure

public int[] ApplyDiscounts(

int maxPercentageAllowed,

Customer[] customers,

Promotion[][] promotions ) {}

Customer

Customer

Customerint

PromotionPromotionPromotion Promotion

Promotion

int int int

Promotion

Microsoft Code Contracts

• Static code verification• Runtime checking, too• Cross-language support• Enhances documentation• Works with .NET Fx 3.5; built into 4.0• Supports pre/post-conditions & invariants• Helper classes for iteration, assertion, etc.

Samples Survey

Sample DescriptionBinarySearch Basics of using the static checkerGCD Studying implicit arithmetic obligationsInterfaceContracts Implementing contracts categoricallyChunker Using invariants for managing edge casesApiProtocols Establishing patterns for state machines

Let's take a look at the Code Contract samples which are excellent for learning how this stuff works.

Contract Reference Assemblies

• Something like "buddy classes" for contracts• Contain visible interface and contracts but no

code bodies• ccrefgen.exe tool can be used to generate• Some have been pre-built and ship with the

Code Contracts installer– Silverlight 3.0 and 4.0– .NET Framework 3.5 and 4.0

Patching Sandcastle

• Open the SandCastle zip file in the Code Contracts installation directory

• Copy the templates into your installed SandCastle folder

• Now help builds from XML comment documentation will include contract information

• A future release of SandCastle should remove the need for patching

Useful URLs

• MSDN Forum for Code Contractssocial.msdn.microsoft.com/Forums/en-IE/codecontracts

• Microsoft Code Contractsresearch.microsoft.com/en-us/projects/contracts

• Kevin's Blogdevjourney.com

Demos

Useful URLs

• MSDN Forum for Code Contractssocial.msdn.microsoft.com/Forums/en-IE/codecontracts

• Microsoft Code Contractsresearch.microsoft.com/en-us/projects/contracts

• Kevin's Blogdevjourney.com

top related