SlideShare a Scribd company logo
Melbourne Patterns Group Presentation
By Clarence Bakirtzidis (clarenceb@gmail.com)
Agenda
 Overview
 Using Code Contracts
 Main Features
 Runtime Contract Checking
 Static Contract Checking
 Demo(s)
 API Reference
 Summary
 Resources
 Questions
* DbC = Design-by-Contract
2
Overview
 What is the Code Contracts API?
 Library with Static Methods for DbC
 It is a spin-off from the learnings of the
Spec# project
 Obtaining and Installing
 Academic and Commercial Licenses
 Tools Provided
 Integration with Visual Studio
3
Overview
 What is Design-by-Contract?
 Originated from Eiffel
 Precondition
○ Condition that is checked on entry to method
 Postcondition
○ Condition that is checked on exit of method
 Invariant (constrain state of objects)
○ Condition checked on exit of constructor and
all public methods and properties
 Static (Compile-time) and Runtime checking
4
Overview
 Benefits of Code Contracts
 Runtime Checking and Improved Testability
 Static Verification
 API Documentation
○ Examples
5
Using Code Contracts
 .NET 4.0
 Part of the Base Class Library (BCL)
 No additional references required
 .NET 3.5 or earlier
 Separate assembly Microsoft.Contracts.dll
 Need to add reference to assembly in your
projects
 Contract classes contains in:
 System.Diagnostics.Contracts namespace
 Code Snippets for Visual Studio
 e.g. ci [TAB][TAB] => Contract.Requires(…)
6
Using Code Contracts
Project Properties
Visual Studio Project Properties
• Runtime Checking
• Static Checking
• Contract Reference Assembly
7
Main Features
 Design-by-Contract
 Runtime Checking
 Static Checking
 Contract Inheritance
 Supports Abstract Methods and Interfaces
 Generate API documentation
 Hooks into XML documentation and inserts
contract requirements (requires, ensures)
8
Runtime Contract Checking
 Configuration options
 Level of checking
 Only public surface contracts
 Call-site requires
 Custom rewriter methods
 Assembly rewriting via ccrewrite.exe
 Inserts code in project assemblies to enforce
contracts at runtime
9
Static Contract Checking
 Configuration options
 Null values
 Array bounds
 Arithmetic (div-by-zero)
 Baseline
 Suppress existing warnings in code base
10
Demo(s)
11
Demo
API Reference
 Preconditions
 Contract.Requires(…)
 EndContractBlock (“legacy-
requires”)
 Postconditions
 Contract.Ensures(…)
 Contract.Ensures<E>(…)
 Contract.EnsuresOnThrow<E>(…)
 Prestate Values
 Contract.Result<T>()
 Contract.OldValue<T>(…)
 Out Parameters
 Contract.ValueAtReturn<T>(…)
 Invariants
 Contract.Invariant(…)
 Attributes
 Pure
 ContractInvariantMethod
 ContractVerification
 ContractPublicPropertyName
 Quantifiers
 Contract.ForAll
 Contract.Exists
 Interfaces and Abstract Methods
 ContractClass
 ContractClassFor
 Other
 Contract.Assert(…)
 Contract.Assume(…)
 ContractException
12
Summary
 Code Contracts bring DbC to the .NET framework
 Provides static and runtime checking of:
 Preconditions
 Postconditions
 Object invariants
 Extends generated XML documentation
 Some known issues (still work in progress)
 Build slowdown - will be addressed in future
 Closures - static checking does not work for closures
 Edit-Continue does not work with code contract rewriting
on
 No contracts allowed on delegates
 No contracts on iterators that use “yield” as IL the code
changed into different form (workaround exists for this)
13
Code Contracts Summary
14
Resources
 Code Contracts Project
 http://research.microsoft.com/en-
us/projects/contracts/
 MSDN Forum
 http://social.msdn.microsoft.com/Forums/en-
US/codecontracts/threads
 Spec# Project
 http://research.microsoft.com/en-
us/projects/specsharp
15
Questions
16

More Related Content

What's hot

Code Generation using T4
Code Generation using T4Code Generation using T4
Code Generation using T4
Joubin Najmaie
 
Back-2-Basics: Exception & Event Instrumentation in .NET
Back-2-Basics: Exception & Event Instrumentation in .NETBack-2-Basics: Exception & Event Instrumentation in .NET
Back-2-Basics: Exception & Event Instrumentation in .NET
David McCarter
 
Why system verilog ?
Why system verilog ? Why system verilog ?
Why system verilog ?
Dr.YNM
 
C++
C++C++
C++
dean129
 
Rock Your Code With Code Contracts -2013
Rock Your Code With Code Contracts -2013Rock Your Code With Code Contracts -2013
Rock Your Code With Code Contracts -2013
David McCarter
 
TDoc - Bringing Documentation to Tool
TDoc - Bringing Documentation to ToolTDoc - Bringing Documentation to Tool
TDoc - Bringing Documentation to Tool
Florian Gysin
 
why c++11?
why c++11?why c++11?
why c++11?
idrajeev
 
Odog : A Framework for Concurrent and Distributed software design
Odog : A Framework for Concurrent and Distributed software designOdog : A Framework for Concurrent and Distributed software design
Odog : A Framework for Concurrent and Distributed software design
ivanjokerbr
 
A tutorial on C++ Programming
A tutorial on C++ ProgrammingA tutorial on C++ Programming
A tutorial on C++ Programming
Prof. Erwin Globio
 

What's hot (9)

Code Generation using T4
Code Generation using T4Code Generation using T4
Code Generation using T4
 
Back-2-Basics: Exception & Event Instrumentation in .NET
Back-2-Basics: Exception & Event Instrumentation in .NETBack-2-Basics: Exception & Event Instrumentation in .NET
Back-2-Basics: Exception & Event Instrumentation in .NET
 
Why system verilog ?
Why system verilog ? Why system verilog ?
Why system verilog ?
 
C++
C++C++
C++
 
Rock Your Code With Code Contracts -2013
Rock Your Code With Code Contracts -2013Rock Your Code With Code Contracts -2013
Rock Your Code With Code Contracts -2013
 
TDoc - Bringing Documentation to Tool
TDoc - Bringing Documentation to ToolTDoc - Bringing Documentation to Tool
TDoc - Bringing Documentation to Tool
 
why c++11?
why c++11?why c++11?
why c++11?
 
Odog : A Framework for Concurrent and Distributed software design
Odog : A Framework for Concurrent and Distributed software designOdog : A Framework for Concurrent and Distributed software design
Odog : A Framework for Concurrent and Distributed software design
 
A tutorial on C++ Programming
A tutorial on C++ ProgrammingA tutorial on C++ Programming
A tutorial on C++ Programming
 

Similar to Code Contracts API In .NET

Conformiq Tutorial
Conformiq TutorialConformiq Tutorial
Conformiq Tutorial
petersmagnusson
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Corba model ppt
Corba model pptCorba model ppt
Corba model ppt
Saransh Garg
 
Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code Contracts
Rainer Stropek
 
Rock Your Code with Code Contracts
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code Contracts
David McCarter
 
Component based software development
Component based software developmentComponent based software development
Component based software development
Emmanuel Fuchs
 
Code contracts by Dmytro Mindra
Code contracts by Dmytro MindraCode contracts by Dmytro Mindra
Code contracts by Dmytro Mindra
Alex Tumanoff
 
Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)
Peter R. Egli
 
WIndows Embedded Compact 2013 – What’s news
WIndows Embedded Compact 2013 – What’s newsWIndows Embedded Compact 2013 – What’s news
WIndows Embedded Compact 2013 – What’s news
Mirco Vanini
 
Enhance Your Code Quality with Code Contracts
Enhance Your Code Quality with Code ContractsEnhance Your Code Quality with Code Contracts
Enhance Your Code Quality with Code Contracts
Eran Stiller
 
Building a web application with ontinuation monads
Building a web application with ontinuation monadsBuilding a web application with ontinuation monads
Building a web application with ontinuation monads
Seitaro Yuuki
 
BizTalk Server Extensibility
BizTalk Server ExtensibilityBizTalk Server Extensibility
BizTalk Server Extensibility
BizTalk360
 
Abstract Factory pattern application on multi-contract on-chain deployments
Abstract Factory pattern application on multi-contract on-chain deploymentsAbstract Factory pattern application on multi-contract on-chain deployments
Abstract Factory pattern application on multi-contract on-chain deployments
Dejan Radic
 
OMG CORBA Component Model tutorial
OMG CORBA Component Model tutorialOMG CORBA Component Model tutorial
OMG CORBA Component Model tutorial
Johnny Willemsen
 
.NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010).NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010)
Koen Metsu
 
Angular 9
Angular 9 Angular 9
Angular 9
Raja Vishnu
 
Building a website with angular
Building a website with angularBuilding a website with angular
Building a website with angular
Joseph Jorden
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builder
Maurizio Vitale
 
How to Create a Service in Choreo
How to Create a Service in ChoreoHow to Create a Service in Choreo
How to Create a Service in Choreo
WSO2
 
Feature and platform testing with CMake
Feature and platform testing with CMakeFeature and platform testing with CMake
Feature and platform testing with CMake
Richard Thomson
 

Similar to Code Contracts API In .NET (20)

Conformiq Tutorial
Conformiq TutorialConformiq Tutorial
Conformiq Tutorial
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Corba model ppt
Corba model pptCorba model ppt
Corba model ppt
 
Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code Contracts
 
Rock Your Code with Code Contracts
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code Contracts
 
Component based software development
Component based software developmentComponent based software development
Component based software development
 
Code contracts by Dmytro Mindra
Code contracts by Dmytro MindraCode contracts by Dmytro Mindra
Code contracts by Dmytro Mindra
 
Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)
 
WIndows Embedded Compact 2013 – What’s news
WIndows Embedded Compact 2013 – What’s newsWIndows Embedded Compact 2013 – What’s news
WIndows Embedded Compact 2013 – What’s news
 
Enhance Your Code Quality with Code Contracts
Enhance Your Code Quality with Code ContractsEnhance Your Code Quality with Code Contracts
Enhance Your Code Quality with Code Contracts
 
Building a web application with ontinuation monads
Building a web application with ontinuation monadsBuilding a web application with ontinuation monads
Building a web application with ontinuation monads
 
BizTalk Server Extensibility
BizTalk Server ExtensibilityBizTalk Server Extensibility
BizTalk Server Extensibility
 
Abstract Factory pattern application on multi-contract on-chain deployments
Abstract Factory pattern application on multi-contract on-chain deploymentsAbstract Factory pattern application on multi-contract on-chain deployments
Abstract Factory pattern application on multi-contract on-chain deployments
 
OMG CORBA Component Model tutorial
OMG CORBA Component Model tutorialOMG CORBA Component Model tutorial
OMG CORBA Component Model tutorial
 
.NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010).NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010)
 
Angular 9
Angular 9 Angular 9
Angular 9
 
Building a website with angular
Building a website with angularBuilding a website with angular
Building a website with angular
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builder
 
How to Create a Service in Choreo
How to Create a Service in ChoreoHow to Create a Service in Choreo
How to Create a Service in Choreo
 
Feature and platform testing with CMake
Feature and platform testing with CMakeFeature and platform testing with CMake
Feature and platform testing with CMake
 

Recently uploaded

LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Undress Baby
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
aymanquadri279
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
Gerardo Pardo-Castellote
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 

Recently uploaded (20)

LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 

Code Contracts API In .NET

  • 1. Melbourne Patterns Group Presentation By Clarence Bakirtzidis (clarenceb@gmail.com)
  • 2. Agenda  Overview  Using Code Contracts  Main Features  Runtime Contract Checking  Static Contract Checking  Demo(s)  API Reference  Summary  Resources  Questions * DbC = Design-by-Contract 2
  • 3. Overview  What is the Code Contracts API?  Library with Static Methods for DbC  It is a spin-off from the learnings of the Spec# project  Obtaining and Installing  Academic and Commercial Licenses  Tools Provided  Integration with Visual Studio 3
  • 4. Overview  What is Design-by-Contract?  Originated from Eiffel  Precondition ○ Condition that is checked on entry to method  Postcondition ○ Condition that is checked on exit of method  Invariant (constrain state of objects) ○ Condition checked on exit of constructor and all public methods and properties  Static (Compile-time) and Runtime checking 4
  • 5. Overview  Benefits of Code Contracts  Runtime Checking and Improved Testability  Static Verification  API Documentation ○ Examples 5
  • 6. Using Code Contracts  .NET 4.0  Part of the Base Class Library (BCL)  No additional references required  .NET 3.5 or earlier  Separate assembly Microsoft.Contracts.dll  Need to add reference to assembly in your projects  Contract classes contains in:  System.Diagnostics.Contracts namespace  Code Snippets for Visual Studio  e.g. ci [TAB][TAB] => Contract.Requires(…) 6
  • 7. Using Code Contracts Project Properties Visual Studio Project Properties • Runtime Checking • Static Checking • Contract Reference Assembly 7
  • 8. Main Features  Design-by-Contract  Runtime Checking  Static Checking  Contract Inheritance  Supports Abstract Methods and Interfaces  Generate API documentation  Hooks into XML documentation and inserts contract requirements (requires, ensures) 8
  • 9. Runtime Contract Checking  Configuration options  Level of checking  Only public surface contracts  Call-site requires  Custom rewriter methods  Assembly rewriting via ccrewrite.exe  Inserts code in project assemblies to enforce contracts at runtime 9
  • 10. Static Contract Checking  Configuration options  Null values  Array bounds  Arithmetic (div-by-zero)  Baseline  Suppress existing warnings in code base 10
  • 12. API Reference  Preconditions  Contract.Requires(…)  EndContractBlock (“legacy- requires”)  Postconditions  Contract.Ensures(…)  Contract.Ensures<E>(…)  Contract.EnsuresOnThrow<E>(…)  Prestate Values  Contract.Result<T>()  Contract.OldValue<T>(…)  Out Parameters  Contract.ValueAtReturn<T>(…)  Invariants  Contract.Invariant(…)  Attributes  Pure  ContractInvariantMethod  ContractVerification  ContractPublicPropertyName  Quantifiers  Contract.ForAll  Contract.Exists  Interfaces and Abstract Methods  ContractClass  ContractClassFor  Other  Contract.Assert(…)  Contract.Assume(…)  ContractException 12
  • 13. Summary  Code Contracts bring DbC to the .NET framework  Provides static and runtime checking of:  Preconditions  Postconditions  Object invariants  Extends generated XML documentation  Some known issues (still work in progress)  Build slowdown - will be addressed in future  Closures - static checking does not work for closures  Edit-Continue does not work with code contract rewriting on  No contracts allowed on delegates  No contracts on iterators that use “yield” as IL the code changed into different form (workaround exists for this) 13
  • 15. Resources  Code Contracts Project  http://research.microsoft.com/en- us/projects/contracts/  MSDN Forum  http://social.msdn.microsoft.com/Forums/en- US/codecontracts/threads  Spec# Project  http://research.microsoft.com/en- us/projects/specsharp 15

Editor's Notes

  1. By Clarence Bakirtzidis (clarenceb@gmail.com) for Melbourne Patterns Group on 02/12/2009.
  2. 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 namespace The 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 Contracts Academic license version can be obtained from Microsoft Research site Commercial license version can be obtained from DevLabs website Standard Edition (no static type checker) – any edition for Visual Studio except Express Edition Includes 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 System Same as Standard Edition but also includes the Static checker Tools include: ccrewrite, for generating runtime checking from the contracts cccheck, 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)
  3. Eiffel was created by Bertrand Meyer in 1985/86 Pure object-oriented language Major feature is Design-by-contract Supports 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 runtime Precondition - is a condition or predicate that must always be true just prior to the execution of some section of code Postcondtion - is a condition or predicate that must always be true just after the execution of some section of code Invariant - 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.
  4. Runtime Checking and Improved Testability Binary rewriter (ccrewriter.exe) modifies a program by injecting the contracts, which are checked as part of program execution. Each contract acts as an oracle, giving a test run a pass/fail indication (oracle:- mechanism used for determining whether a test has been passed or failed, e.g. Assert.True) Automatic testing tools, such as Pex, can take advantage of contracts to generate more meaningful unit tests by filtering out meaningless test arguments that don't satisfy the pre-conditions. Static Verification Static checker can determine if there are any contract errors without running the program (and all violations rather than just a particular executed path as with runtime) No foolproof. Sometimes the checker gets confused and cannot prove contracts are satisfied (e.g. when preconditions rely on existing state of the object, e.g. amout < balance). Can assist static check by using Contract.Assert and Contract.Assume Checks for implicit contracts, such as null dereferences and array bounds, as well as the explicit contracts API Documentation Document generator (ccdoc.exe) augments the existing XML doc files with contract information. Documentation is now kept up to date from code (no need to maintain pre/postconditions, invariants manually in XML comments) Also includes new stylesheets for Sandcastle so that generated documentation pages have contract sections.
  5. Code Contracts will ship bundled with .NET 4.0.  (Static Type Checker will be available with VS2010 Ultimate only)
  6. Contract Reference Assembly Without building a contract reference assembly, other projects cannot determine what contracts are present.
  7. Static Checking By default tries to prove explicit contract checks (on build): Assertions, invariants, requires, ensures, inherited ensures, requires methods in referenced assemblies, object invariants on classes extending base classes and interfaces in other assemblies Runtime Checking Contract rewriter places runtime checks in the assemblies at appropriate places Contract Inheritance Code contracts support behavioural subtyping where contracts are enforced in subtypes of the parent type where the contracts are defined. Subtypes cannot add any preconditions as this may further constrain the contract (and MS see no practical use for weakening the contract). If supertype does not declare any preconditions then the subtype is still not allowed to add any Method preconditions must be declared on the root method of an inheritance/implementation chain, i.e., the first virtual or abstract method declaration, or the interface method itself. Postconditions can be added in subtypes (adding further postconditions gives client more guarantees than before).  They are effectively conjoined ("and"-ed) with the supertype postconditions Object invariants are also inherited.  They are enforced on the type they were declared on and any subtypes. Base class invariants are enforced at runtime automatically provided the assembly containing the base class has contract runtime checking enabled.  Therefore, do not invokes the base class object invariant from your code.
  8. Level of checking Explain the API and "perfect world" scenarios where everything is enabled for run-time and release builds Then explain why you might want to disable checking in release builds and what options you have (e.g. legacy requires, contract assemblies) Contract Rewriting The contract rewriter performs several tasks: postconditions are moved to the end of the method body method return values are substituted for occurrences of Contract. Result<T>() pre-state values are sub- stituted for occurrences of Contract.OldValue<T>(). In addition, contract inheritance is performed.
  9. Use “Binary Search” demo from Code Contracts samples as a basis for discussing static checking behaviour Explain array bound, null, arithmetic (div-by-zero) checking Time permitting, “Chunker” is also a good example for object invariants and static checking
  10. Can use System.Linq.Enumerable.All instead of Contract.ForAll in Pre and Postconditions. Can use System.Ling.Enumerable.Any instead of Contract.Exists in Pre and Postconditions. ContractException Is not a public type but written into each assembly as a nested private type and thus cannot be caught by your code (you shouldn't be writing code to catch contract exceptions!)
  11. Why not just use Debug.Asserts instead of Contract.Requires, etc? Preconditions should establish conditions for caller prior to calling method and hence should only refer to state visible to caller. Debug.Asserts can be use to refer to internal consistency. Postconditions: usnig Debug.Assert everywhere the method can exit is error prone and tedious. With contracts you specify the postcondition once at the start of the method. Contracts can be inherited and avoid repeating checks over and over in subtypes. Contracts can be used to generate API documentation [Extracted from the Microsoft Code Contracts FAQ]
  12. Credits: Cube image is from http://lostmitten.org/