Using the Code Contracts API for design-by-contract in .NETMelbourne Patterns Group PresentationBy Clarence Bakirtzidis(clarenceb@gmail.com)
AgendaOverviewUsing Code ContractsMain FeaturesRuntime Contract CheckingStatic Contract CheckingDemo(s)API ReferenceSummaryResourcesQuestions* DbC = Design-by-Contract2
OverviewWhat is the Code Contracts API?Library with Static Methods for DbCIt is a spin-off from the learnings of the Spec# projectObtaining and InstallingAcademic and Commercial LicensesTools ProvidedIntegration with Visual Studio3
OverviewWhat is Design-by-Contract?Originated from EiffelPreconditionCondition that is checked on entry to methodPostconditionCondition that is checked on exit of methodInvariant (constrain state of objects)Condition checked on exit of constructor and all public methods and propertiesStatic (Compile-time) and Runtime checking4
OverviewBenefits of Code ContractsRuntime Checking and Improved TestabilityStatic VerificationAPI DocumentationExamples5
Using Code Contracts.NET 4.0Part of the Base Class Library (BCL)No additional references required.NET 3.5 or earlierSeparate assembly Microsoft.Contracts.dllNeed to add reference to assembly in your projectsContract classes contains in:System.Diagnostics.Contracts namespaceCode Snippetsfor Visual Studioe.g. ci [TAB][TAB] => Contract.Requires(…)6
Using Code ContractsVisual Studio Project PropertiesRuntime Checking
Static Checking
Contract Reference AssemblyProject Properties7
Main FeaturesDesign-by-ContractRuntime CheckingStatic CheckingContract InheritanceSupports Abstract Methods and InterfacesGenerate API documentationHooks into XML documentation and inserts contract requirements (requires, ensures)8
Runtime Contract CheckingConfiguration optionsLevel of checkingOnly public surface contractsCall-site requiresCustom rewriter methodsAssembly rewriting via ccrewrite.exeInserts code in project assemblies to enforce contracts at runtime9
Static Contract CheckingConfiguration optionsNull valuesArray boundsArithmetic (div-by-zero)BaselineSuppress existing warnings in code base10
Demo(s)11Demo
API ReferencePreconditionsContract.Requires(…)EndContractBlock (“legacy-requires”)PostconditionsContract.Ensures(…)Contract.Ensures<E>(…)Contract.EnsuresOnThrow<E>(…)Prestate ValuesContract.Result<T>()Contract.OldValue<T>(…)OutParametersContract.ValueAtReturn<T>(…)InvariantsContract.Invariant(…)AttributesPureContractInvariantMethodContractVerificationContractPublicPropertyNameQuantifiersContract.ForAllContract.ExistsInterfacesandAbstractMethodsContractClassContractClassForOtherContract.Assert(…)Contract.Assume(…)ContractException12
SummaryCode Contracts bring DbC to the .NET frameworkProvides static and runtime checking of:PreconditionsPostconditionsObject invariantsExtends generated XML documentationSome known issues (still work in progress)Build slowdown - will be addressed in futureClosures - static checking does not work for closuresEdit-Continue does not work with code contract rewriting onNo contracts allowed on delegatesNo contracts on iterators that use “yield” as IL the code changed into different form (workaround exists for this)13
Code Contracts Summary14

Code Contracts API In .Net

  • 1.
    Using the CodeContracts API for design-by-contract in .NETMelbourne Patterns Group PresentationBy Clarence Bakirtzidis(clarenceb@gmail.com)
  • 2.
    AgendaOverviewUsing Code ContractsMainFeaturesRuntime Contract CheckingStatic Contract CheckingDemo(s)API ReferenceSummaryResourcesQuestions* DbC = Design-by-Contract2
  • 3.
    OverviewWhat is theCode Contracts API?Library with Static Methods for DbCIt is a spin-off from the learnings of the Spec# projectObtaining and InstallingAcademic and Commercial LicensesTools ProvidedIntegration with Visual Studio3
  • 4.
    OverviewWhat is Design-by-Contract?Originatedfrom EiffelPreconditionCondition that is checked on entry to methodPostconditionCondition that is checked on exit of methodInvariant (constrain state of objects)Condition checked on exit of constructor and all public methods and propertiesStatic (Compile-time) and Runtime checking4
  • 5.
    OverviewBenefits of CodeContractsRuntime Checking and Improved TestabilityStatic VerificationAPI DocumentationExamples5
  • 6.
    Using Code Contracts.NET4.0Part of the Base Class Library (BCL)No additional references required.NET 3.5 or earlierSeparate assembly Microsoft.Contracts.dllNeed to add reference to assembly in your projectsContract classes contains in:System.Diagnostics.Contracts namespaceCode Snippetsfor Visual Studioe.g. ci [TAB][TAB] => Contract.Requires(…)6
  • 7.
    Using Code ContractsVisualStudio Project PropertiesRuntime Checking
  • 8.
  • 9.
  • 10.
    Main FeaturesDesign-by-ContractRuntime CheckingStaticCheckingContract InheritanceSupports Abstract Methods and InterfacesGenerate API documentationHooks into XML documentation and inserts contract requirements (requires, ensures)8
  • 11.
    Runtime Contract CheckingConfigurationoptionsLevel of checkingOnly public surface contractsCall-site requiresCustom rewriter methodsAssembly rewriting via ccrewrite.exeInserts code in project assemblies to enforce contracts at runtime9
  • 12.
    Static Contract CheckingConfigurationoptionsNull valuesArray boundsArithmetic (div-by-zero)BaselineSuppress existing warnings in code base10
  • 13.
  • 14.
    API ReferencePreconditionsContract.Requires(…)EndContractBlock (“legacy-requires”)PostconditionsContract.Ensures(…)Contract.Ensures<E>(…)Contract.EnsuresOnThrow<E>(…)PrestateValuesContract.Result<T>()Contract.OldValue<T>(…)OutParametersContract.ValueAtReturn<T>(…)InvariantsContract.Invariant(…)AttributesPureContractInvariantMethodContractVerificationContractPublicPropertyNameQuantifiersContract.ForAllContract.ExistsInterfacesandAbstractMethodsContractClassContractClassForOtherContract.Assert(…)Contract.Assume(…)ContractException12
  • 15.
    SummaryCode Contracts bringDbC to the .NET frameworkProvides static and runtime checking of:PreconditionsPostconditionsObject invariantsExtends generated XML documentationSome known issues (still work in progress)Build slowdown - will be addressed in futureClosures - static checking does not work for closuresEdit-Continue does not work with code contract rewriting onNo contracts allowed on delegatesNo contracts on iterators that use “yield” as IL the code changed into different form (workaround exists for this)13
  • 16.

Editor's Notes

  • #2 By Clarence Bakirtzidis (clarenceb@gmail.com) for Melbourne Patterns Group on 02/12/2009.
  • #4 What is Code Contracts API? (From Microsoft Research)"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. Contracts act as checked documentation of your external and internal APIs. The contracts are used to improve testing via runtime checking, enable static contract verification, and documentation generation." Library consists of a set of static methods in the System.Diagnostics.Contract namespaceThe use of a library has the advantage that all .NET languages can immediately take advantage of contracts immediately.Spec# is a Microsoft Research project which extends the C# language with constructs for non-null types, preconditions, postconditions, and object invariants.It is a more advanced research project than Code ContractsAcademic license version can be obtained from Microsoft Research siteCommercial license version can be obtained from DevLabs websiteStandard Edition (no static type checker) – any edition for Visual Studio except Express EditionIncludes the stand-alone contract library, the binary rewriter (for runtime checking), the reference assembly generator, and a set of reference assemblies for the .NET Framework.VSTS Edition (includes static type checker) – Only for Visual Studio Team SystemSame as Standard Edition but also includes the Static checkerTools include:ccrewrite, for generating runtime checking from the contractscccheck, a static checker that verifies contracts at compile-time.ccdoc,  a tool that adds contracts to the XML documentation files and to Sandcastle-generated MSDN-style help files.Plan is to add further tools. There is a prototype for a VS 2010 add-in so that inherited contracts show up as you type.Integration includes properties tab called “Code Contracts” for VS projects (can enable/disable various features)
  • #5 Eiffel was created by Bertrand Meyer in 1985/86Pure object-oriented languageMajor feature is Design-by-contractSupports preconditions, postconditions, invariants, loop invariants, loop variants (ensure loop will end), check (like C assert)Can choose to enable only preconditions (e.g. for 3pp code) to reduce contract checking"void safety" - void is null in Eiffel.  e.g. x.f where x is null the compiler can detect if this will succeed at runtimePrecondition - is a condition or predicate that must always be true just prior to the execution of some section of codePostcondtion - is a condition or predicate that must always be true just after the execution of some section of codeInvariant - invariants constrain the state stored in the object.  Methods of the class should preserve the invariant. Class invariants are established during construction and constantly maintained between calls to public methods. Temporary breaking of class invariance between private method calls is possible, although not encouraged.