SlideShare una empresa de Scribd logo
1 de 16
Using the Code Contracts API for design-by-contract in .NET 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 Snippetsfor Visual Studio e.g. ci [TAB][TAB] => Contract.Requires(…) 6
Using Code Contracts Visual Studio Project Properties ,[object Object]
Static Checking
Contract Reference AssemblyProject Properties 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>(…) OutParameters Contract.ValueAtReturn<T>(…) Invariants Contract.Invariant(…) Attributes Pure ContractInvariantMethod ContractVerification ContractPublicPropertyName Quantifiers Contract.ForAll Contract.Exists InterfacesandAbstractMethods 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

Más contenido relacionado

La actualidad más candente

Codemotion tech pills - Continuous performance
Codemotion tech pills  - Continuous performanceCodemotion tech pills  - Continuous performance
Codemotion tech pills - Continuous performanceBert Jan Schrijver
 
Amsterdam JUG - Continuous performance
Amsterdam JUG - Continuous performanceAmsterdam JUG - Continuous performance
Amsterdam JUG - Continuous performanceBert Jan Schrijver
 
Get together on getting more out of typescript & angular 2
Get together on getting more out of typescript & angular 2Get together on getting more out of typescript & angular 2
Get together on getting more out of typescript & angular 2Ruben Haeck
 

La actualidad más candente (6)

Automatic Test 2019-07-25
Automatic Test 2019-07-25Automatic Test 2019-07-25
Automatic Test 2019-07-25
 
Codemotion tech pills - Continuous performance
Codemotion tech pills  - Continuous performanceCodemotion tech pills  - Continuous performance
Codemotion tech pills - Continuous performance
 
Amsterdam JUG - Continuous performance
Amsterdam JUG - Continuous performanceAmsterdam JUG - Continuous performance
Amsterdam JUG - Continuous performance
 
I++ unit testing
I++ unit testingI++ unit testing
I++ unit testing
 
Get together on getting more out of typescript & angular 2
Get together on getting more out of typescript & angular 2Get together on getting more out of typescript & angular 2
Get together on getting more out of typescript & angular 2
 
C# 6
C# 6C# 6
C# 6
 

Similar a Code Contracts API In .Net

Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code ContractsRainer Stropek
 
Component based software development
Component based software developmentComponent based software development
Component based software developmentEmmanuel Fuchs
 
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 newsMirco Vanini
 
你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)
你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)
你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)Will Huang
 
BizTalk Server Extensibility
BizTalk Server ExtensibilityBizTalk Server Extensibility
BizTalk Server ExtensibilityBizTalk360
 
Building a website with angular
Building a website with angularBuilding a website with angular
Building a website with angularJoseph Jorden
 
OMG CORBA Component Model tutorial
OMG CORBA Component Model tutorialOMG CORBA Component Model tutorial
OMG CORBA Component Model tutorialJohnny Willemsen
 
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009Monorail presentation at WebDevelopersCommunity, Feb 1, 2009
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009ken.egozi
 
Accordion Pipelines - A Cloud-native declarative Pipelines and Dynamic workfl...
Accordion Pipelines - A Cloud-native declarative Pipelines and Dynamic workfl...Accordion Pipelines - A Cloud-native declarative Pipelines and Dynamic workfl...
Accordion Pipelines - A Cloud-native declarative Pipelines and Dynamic workfl...Cisco Tech Blog
 
The Internal Architecture of Chrome Developer Tools
The Internal Architecture of Chrome Developer ToolsThe Internal Architecture of Chrome Developer Tools
The Internal Architecture of Chrome Developer ToolsMiroslav Bajtoš
 
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 ChoreoWSO2
 
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 ContractsEran Stiller
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builderMaurizio Vitale
 

Similar a Code Contracts API In .Net (20)

Code Contracts API In .NET
Code Contracts API In .NETCode Contracts API In .NET
Code Contracts API In .NET
 
Conformiq Tutorial
Conformiq TutorialConformiq Tutorial
Conformiq Tutorial
 
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
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Component based software development
Component based software developmentComponent based software development
Component based software development
 
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
 
你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)
你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)
你不可不知的 ASP.NET Core 3 全新功能探索 (.NET Conf 2019)
 
BizTalk Server Extensibility
BizTalk Server ExtensibilityBizTalk Server Extensibility
BizTalk Server Extensibility
 
Building a website with angular
Building a website with angularBuilding a website with angular
Building a website with angular
 
Angular 9
Angular 9 Angular 9
Angular 9
 
OMG CORBA Component Model tutorial
OMG CORBA Component Model tutorialOMG CORBA Component Model tutorial
OMG CORBA Component Model tutorial
 
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009Monorail presentation at WebDevelopersCommunity, Feb 1, 2009
Monorail presentation at WebDevelopersCommunity, Feb 1, 2009
 
Accordion Pipelines - A Cloud-native declarative Pipelines and Dynamic workfl...
Accordion Pipelines - A Cloud-native declarative Pipelines and Dynamic workfl...Accordion Pipelines - A Cloud-native declarative Pipelines and Dynamic workfl...
Accordion Pipelines - A Cloud-native declarative Pipelines and Dynamic workfl...
 
The Internal Architecture of Chrome Developer Tools
The Internal Architecture of Chrome Developer ToolsThe Internal Architecture of Chrome Developer Tools
The Internal Architecture of Chrome Developer Tools
 
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
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
 
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
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builder
 

Más de melbournepatterns (20)

An Introduction to
An Introduction to An Introduction to
An Introduction to
 
State Pattern from GoF
State Pattern from GoFState Pattern from GoF
State Pattern from GoF
 
Iterator Pattern
Iterator PatternIterator Pattern
Iterator Pattern
 
Iterator
IteratorIterator
Iterator
 
Concurrency Patterns
Concurrency PatternsConcurrency Patterns
Concurrency Patterns
 
Continuous Integration, Fast Builds and Flot
Continuous Integration, Fast Builds and FlotContinuous Integration, Fast Builds and Flot
Continuous Integration, Fast Builds and Flot
 
Command Pattern
Command PatternCommand Pattern
Command Pattern
 
LINQ/PLINQ
LINQ/PLINQLINQ/PLINQ
LINQ/PLINQ
 
Gpu Cuda
Gpu CudaGpu Cuda
Gpu Cuda
 
Facade Pattern
Facade PatternFacade Pattern
Facade Pattern
 
Phani Kumar - Decorator Pattern
Phani Kumar - Decorator PatternPhani Kumar - Decorator Pattern
Phani Kumar - Decorator Pattern
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Prototype Design Pattern
Prototype Design PatternPrototype Design Pattern
Prototype Design Pattern
 
Factory Method Design Pattern
Factory Method Design PatternFactory Method Design Pattern
Factory Method Design Pattern
 
Abstract Factory Design Pattern
Abstract Factory Design PatternAbstract Factory Design Pattern
Abstract Factory Design Pattern
 
A Little Lisp
A Little LispA Little Lisp
A Little Lisp
 
State Pattern in Flex
State Pattern in FlexState Pattern in Flex
State Pattern in Flex
 
Active Object
Active ObjectActive Object
Active Object
 
Extract Composite Talk Andy
Extract Composite Talk AndyExtract Composite Talk Andy
Extract Composite Talk Andy
 

Último

AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 

Último (20)

AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

Code Contracts API In .Net

  • 1. Using the Code Contracts API for design-by-contract in .NET 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 Snippetsfor Visual Studio e.g. ci [TAB][TAB] => Contract.Requires(…) 6
  • 7.
  • 10. 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
  • 11. 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
  • 12. Static Contract Checking Configuration options Null values Array bounds Arithmetic (div-by-zero) Baseline Suppress existing warnings in code base 10
  • 14. 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>(…) OutParameters Contract.ValueAtReturn<T>(…) Invariants Contract.Invariant(…) Attributes Pure ContractInvariantMethod ContractVerification ContractPublicPropertyName Quantifiers Contract.ForAll Contract.Exists InterfacesandAbstractMethods ContractClass ContractClassFor Other Contract.Assert(…) Contract.Assume(…) ContractException 12
  • 15. 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
  • 17. 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

Notas del editor

  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 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)
  3. 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.