SlideShare una empresa de Scribd logo
1 de 22
Code Contracts
   Enhance Your Code Quality with Code Contracts

Eran Stiller
Senior Software
Architect, Founder
March 20, 2013
About Me
•   Software architect, consultant and instructor
•   Technology addict
•   10 years of experience
•   .NET and Native Windows Programming
•   Specializes in large-scale, server-side, highly-concurrent systems
•   Co-Founder at CodeValue Ltd.
•   http://stiller.co.il/blog
Agenda
• Back to Basics
• Design by Contract
• Code Contracts
  – Preconditions
  – Postconditions
  – Invariants
• Internals
• External Tools
Back to Basics
The If…Throw Approach
public class MyClass
{
       public void SomeMethod(string s, int i)
       {
              if (s == null)
                     throw new ArgumentNullException(
                            "s", "Your input string cannot be null!");
              if (i < 0)
                     throw new ArgumentException(
                            "Your input must be non-negative!", "i");

             // Your code here
        }
}
The If…Throw Approach
• Issues
  – Cumbersome – lots of code
  – Indistinguishable from method code
  – Does not apply to interfaces
  – Does not apply across object inheritance
  – Not visible at call site
  – Not part of the contract
Design by Contract
“Design by contract (DbC) (…) is an approach for
designing software. It prescribes that software
designers should define formal, precise and verifiable interface
specifications for software components, which extend the
ordinary definition of abstract data types with preconditions,
postconditions and invariants. These specifications are referred
to as "contracts", in accordance with a conceptual metaphor
with the conditions and obligations of business contracts.”
(Wikipedia)
Enter Code Contracts
• Microsoft’s Design-by-Contract
  implementation for .NET
  – A subset of Spec#
• Language-agnostic way to express coding assumptions
• Checked documentation of your API
  – Improved testability
  – Static verification
  – API documentation
Requirements
• .NET 4.0/4.5
• Visual Studio 2010/2012
  – Any edition except “Express” edition
• Download and install from Microsoft Research
  – http://research.microsoft.com/en-us/projects/contracts/
• Allowed for commercial use

• In addition
  – Support exists for .NET 3.5 and VS 2008 as well
  – Contracts API is part of an external assembly
Preconditions
• Define what your API expects
  – Parameter validation
  – Object state
  – Environment condition
  – Anything the caller can check!
Postconditions
• Define what the caller can expect from your API
  – Return value constraints
  – Exception constraints
  – Object state after call
Invariants
• Define the rules which govern your object’s behavior
  – Object state
  – Field & property values
  – Things that always hold true
Enough Talking. Show Me the Code!
Should I Use It? It Depends…
• Pros
  –   Reduce bugs
  –   Static verification
  –   API documentation
  –   Improved testability
  –   Shallow learning curve
• Cons
  –   Experimental project
  –   Static verifier less than perfect
  –   Some issues with VS2012
  –   Compilation time increase
There is a Middle Way!
public class MyClass
{
        public void SomeMethod(string s, int i)
        {
                if (s == null)
                        throw new ArgumentNullException(
                                "s", "Your input string cannot be null!");
                if (i < 0)
                        throw new ArgumentException(
                                "Your input must be non-negative!", "i");
                 Contract.EndContractBlock();

               // Your code here
        }
}
How Can I Choose?
 From the
 User Manual
Code Contracts Internals
• Contract Rewriter
   – ccrewrite
• Static Verifier
   – cccheck
• API Documentation
   – ccdoc
• Ships with contract assemblies for many BCL types & methods
Code Contracts Internals
Code Contracts Editor Extension
• Visual Studio 2010 Only
  – 2012 support still pending
  – http://tinyurl.com/CCEditorExtensions
• Has some stability issues
Summary
• A contract is more than an Interface
• Design by Contract is a design approach
• Code Contracts enables Design by Contract on .NET
    – Preconditions, Postconditions & Invariants
•   An experimental project from Microsoft Research
•   Rewrites your application’s IL code
•   Integrates with Editor Extensions & Pex
•   Give it a try!
Resources
• My Blog
  – http://stiller.co.il/blog
• Code Contracts
  – http://research.microsoft.com/en-us/projects/contracts/
  – http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf
  – http://social.msdn.microsoft.com/Forums/en-US/codecontracts/threads
• Design by Contract
  – http://en.wikipedia.org/wiki/Design_by_contract
• Pex
  – http://research.microsoft.com/en-us/projects/pex/
Presenter contact details
c: +972-54-6160646
e: erans@codevalue.net
b: stiller.co.il/blog
w: www.codevalue.net

Más contenido relacionado

La actualidad más candente

Current Testing Challenges Ireland
Current Testing Challenges IrelandCurrent Testing Challenges Ireland
Current Testing Challenges Ireland
David O'Dowd
 
Beyond Unit Testing
Beyond Unit TestingBeyond Unit Testing
Beyond Unit Testing
Søren Lund
 

La actualidad más candente (19)

Writing Testable Code in SharePoint
Writing Testable Code in SharePointWriting Testable Code in SharePoint
Writing Testable Code in SharePoint
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Code review
Code reviewCode review
Code review
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code Review
 
Current Testing Challenges Ireland
Current Testing Challenges IrelandCurrent Testing Challenges Ireland
Current Testing Challenges Ireland
 
Documenting code yapceu2016
Documenting code yapceu2016Documenting code yapceu2016
Documenting code yapceu2016
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Documenting Code - Patterns and Anti-patterns - NLPW 2016
Documenting Code - Patterns and Anti-patterns - NLPW 2016Documenting Code - Patterns and Anti-patterns - NLPW 2016
Documenting Code - Patterns and Anti-patterns - NLPW 2016
 
Design for Testability in Practice
Design for Testability in PracticeDesign for Testability in Practice
Design for Testability in Practice
 
Mca 02 year_exp_unit_automation_testing_ldra_rtrt_c -
Mca 02 year_exp_unit_automation_testing_ldra_rtrt_c -Mca 02 year_exp_unit_automation_testing_ldra_rtrt_c -
Mca 02 year_exp_unit_automation_testing_ldra_rtrt_c -
 
LogiLogicless UI prototyping with Node.js | SuperSpeaker@CodeCamp Iasi, 2014
LogiLogicless UI prototyping with Node.js | SuperSpeaker@CodeCamp Iasi, 2014LogiLogicless UI prototyping with Node.js | SuperSpeaker@CodeCamp Iasi, 2014
LogiLogicless UI prototyping with Node.js | SuperSpeaker@CodeCamp Iasi, 2014
 
Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...
Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...
Clean Code I - Design Patterns and Best Practices at SoCal Code Camp San Dieg...
 
Code Review Best Practices
Code Review Best PracticesCode Review Best Practices
Code Review Best Practices
 
API Design - developing for developers
API Design - developing for developersAPI Design - developing for developers
API Design - developing for developers
 
Lessons Learnt from Backend Systems Development
Lessons Learnt from Backend Systems DevelopmentLessons Learnt from Backend Systems Development
Lessons Learnt from Backend Systems Development
 
TDD and BDD in Sky Deutschland
TDD and BDD in Sky DeutschlandTDD and BDD in Sky Deutschland
TDD and BDD in Sky Deutschland
 
Open sourcing Adyen’s API explorer
Open sourcing Adyen’s API explorerOpen sourcing Adyen’s API explorer
Open sourcing Adyen’s API explorer
 
BDD and Behave
BDD and BehaveBDD and Behave
BDD and Behave
 
Beyond Unit Testing
Beyond Unit TestingBeyond Unit Testing
Beyond Unit Testing
 

Similar a Enhance Your Code Quality with Code Contracts

NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET
Dmytro Mindra
 
Clean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code CampClean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code Camp
Theo Jungeblut
 

Similar a Enhance Your Code Quality with Code Contracts (20)

NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET NetWork - 15.10.2011 - Applied code generation in .NET
NetWork - 15.10.2011 - Applied code generation in .NET
 
Crafting ColdFusion Applications like an Architect
Crafting ColdFusion Applications like an ArchitectCrafting ColdFusion Applications like an Architect
Crafting ColdFusion Applications like an Architect
 
Clean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code CampClean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code Camp
 
Binary Studio Academy: .NET Code Testing
Binary Studio Academy: .NET Code TestingBinary Studio Academy: .NET Code Testing
Binary Studio Academy: .NET Code Testing
 
Old code doesn't stink
Old code doesn't stinkOld code doesn't stink
Old code doesn't stink
 
10 Reasons You MUST Consider Pattern-Aware Programming
10 Reasons You MUST Consider Pattern-Aware Programming10 Reasons You MUST Consider Pattern-Aware Programming
10 Reasons You MUST Consider Pattern-Aware Programming
 
Code quality
Code qualityCode quality
Code quality
 
NET Code Testing
NET Code TestingNET Code Testing
NET Code Testing
 
Enterprise Node - Code Quality
Enterprise Node - Code QualityEnterprise Node - Code Quality
Enterprise Node - Code Quality
 
CBDW2014 - Behavior Driven Development with TestBox
CBDW2014 - Behavior Driven Development with TestBoxCBDW2014 - Behavior Driven Development with TestBox
CBDW2014 - Behavior Driven Development with TestBox
 
Coding Naked
Coding NakedCoding Naked
Coding Naked
 
A Tale of Two Pizzas: Accelerating Software Delivery with AWS Developer Tools
A Tale of Two Pizzas: Accelerating Software Delivery with AWS Developer ToolsA Tale of Two Pizzas: Accelerating Software Delivery with AWS Developer Tools
A Tale of Two Pizzas: Accelerating Software Delivery with AWS Developer Tools
 
Enter the mind of an Agile Developer
Enter the mind of an Agile DeveloperEnter the mind of an Agile Developer
Enter the mind of an Agile Developer
 
ENT201 A Tale of Two Pizzas: Accelerating Software Delivery with AWS Develope...
ENT201 A Tale of Two Pizzas: Accelerating Software Delivery with AWS Develope...ENT201 A Tale of Two Pizzas: Accelerating Software Delivery with AWS Develope...
ENT201 A Tale of Two Pizzas: Accelerating Software Delivery with AWS Develope...
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Autoframework design
Autoframework designAutoframework design
Autoframework design
 
Writing less code with Serverless on AWS at AWS User Group Nairobi
Writing less code with Serverless on AWS at AWS User Group NairobiWriting less code with Serverless on AWS at AWS User Group Nairobi
Writing less code with Serverless on AWS at AWS User Group Nairobi
 
AspectMock
AspectMockAspectMock
AspectMock
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 
Wavect - Your long-term partner for sophisticated and maintainable software
Wavect - Your long-term partner for sophisticated and maintainable softwareWavect - Your long-term partner for sophisticated and maintainable software
Wavect - Your long-term partner for sophisticated and maintainable software
 

Más de Eran Stiller

Más de Eran Stiller (20)

Architecting at Scale with the Advice Process
Architecting at Scale with the Advice ProcessArchitecting at Scale with the Advice Process
Architecting at Scale with the Advice Process
 
Application Evolution Strategy
Application Evolution StrategyApplication Evolution Strategy
Application Evolution Strategy
 
Developing and Deploying Microservices with Project Tye
Developing and Deploying Microservices with Project TyeDeveloping and Deploying Microservices with Project Tye
Developing and Deploying Microservices with Project Tye
 
API Design in the Modern Era - Architecture Next 2020
API Design in the Modern Era - Architecture Next 2020API Design in the Modern Era - Architecture Next 2020
API Design in the Modern Era - Architecture Next 2020
 
Bot-Tender: A Chat Bot Walks into a Bar (2020)
Bot-Tender: A Chat Bot Walks into a Bar (2020)Bot-Tender: A Chat Bot Walks into a Bar (2020)
Bot-Tender: A Chat Bot Walks into a Bar (2020)
 
Why Don’t You Understand Me? Build Intelligence into Your Apps
Why Don’t You Understand Me? Build Intelligence into Your AppsWhy Don’t You Understand Me? Build Intelligence into Your Apps
Why Don’t You Understand Me? Build Intelligence into Your Apps
 
Modern Microservices Architecture with Docker
Modern Microservices Architecture with DockerModern Microservices Architecture with Docker
Modern Microservices Architecture with Docker
 
Windows Containers - Microsoft Ignite The Tour
Windows Containers - Microsoft Ignite The TourWindows Containers - Microsoft Ignite The Tour
Windows Containers - Microsoft Ignite The Tour
 
Architecting Multitenant SaaS Applications with Azure - Microsoft Ignite The ...
Architecting Multitenant SaaS Applications with Azure - Microsoft Ignite The ...Architecting Multitenant SaaS Applications with Azure - Microsoft Ignite The ...
Architecting Multitenant SaaS Applications with Azure - Microsoft Ignite The ...
 
Bot Framework - Microsoft Ignite The Tour
Bot Framework - Microsoft Ignite The TourBot Framework - Microsoft Ignite The Tour
Bot Framework - Microsoft Ignite The Tour
 
It's a Serverless World
It's a Serverless WorldIt's a Serverless World
It's a Serverless World
 
Keynote - From Monolith to Microservices - Lessons Learned in the Real World
Keynote - From Monolith to Microservices - Lessons Learned in the Real WorldKeynote - From Monolith to Microservices - Lessons Learned in the Real World
Keynote - From Monolith to Microservices - Lessons Learned in the Real World
 
Architecting a Serverless IoT System in the Cloud
Architecting a Serverless IoT System in the CloudArchitecting a Serverless IoT System in the Cloud
Architecting a Serverless IoT System in the Cloud
 
6 Lessons I Learned on my Journey from Monolith to Microservices
6 Lessons I Learned on my Journey from Monolith to Microservices6 Lessons I Learned on my Journey from Monolith to Microservices
6 Lessons I Learned on my Journey from Monolith to Microservices
 
IoT in Action Keynote - CodeValue
IoT in Action Keynote - CodeValueIoT in Action Keynote - CodeValue
IoT in Action Keynote - CodeValue
 
Net Conf Israel - Intro & Building Cloud Native Apps with .NET Core 3.0 and K...
Net Conf Israel - Intro & Building Cloud Native Apps with .NET Core 3.0 and K...Net Conf Israel - Intro & Building Cloud Native Apps with .NET Core 3.0 and K...
Net Conf Israel - Intro & Building Cloud Native Apps with .NET Core 3.0 and K...
 
Create Your Own Serverless PKI with .NET & Azure Key Vault
Create Your Own Serverless PKI with .NET & Azure Key VaultCreate Your Own Serverless PKI with .NET & Azure Key Vault
Create Your Own Serverless PKI with .NET & Azure Key Vault
 
Cloud Native Development on Azure
Cloud Native Development on AzureCloud Native Development on Azure
Cloud Native Development on Azure
 
Today, the Cloud Is Your Advantage
Today, the Cloud Is Your AdvantageToday, the Cloud Is Your Advantage
Today, the Cloud Is Your Advantage
 
Build 2019 Recap
Build 2019 RecapBuild 2019 Recap
Build 2019 Recap
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

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...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
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
 
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
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

Enhance Your Code Quality with Code Contracts

  • 1. Code Contracts Enhance Your Code Quality with Code Contracts Eran Stiller Senior Software Architect, Founder March 20, 2013
  • 2. About Me • Software architect, consultant and instructor • Technology addict • 10 years of experience • .NET and Native Windows Programming • Specializes in large-scale, server-side, highly-concurrent systems • Co-Founder at CodeValue Ltd. • http://stiller.co.il/blog
  • 3. Agenda • Back to Basics • Design by Contract • Code Contracts – Preconditions – Postconditions – Invariants • Internals • External Tools
  • 5. The If…Throw Approach public class MyClass { public void SomeMethod(string s, int i) { if (s == null) throw new ArgumentNullException( "s", "Your input string cannot be null!"); if (i < 0) throw new ArgumentException( "Your input must be non-negative!", "i"); // Your code here } }
  • 6. The If…Throw Approach • Issues – Cumbersome – lots of code – Indistinguishable from method code – Does not apply to interfaces – Does not apply across object inheritance – Not visible at call site – Not part of the contract
  • 7. Design by Contract “Design by contract (DbC) (…) is an approach for designing software. It prescribes that software designers should define formal, precise and verifiable interface specifications for software components, which extend the ordinary definition of abstract data types with preconditions, postconditions and invariants. These specifications are referred to as "contracts", in accordance with a conceptual metaphor with the conditions and obligations of business contracts.” (Wikipedia)
  • 8. Enter Code Contracts • Microsoft’s Design-by-Contract implementation for .NET – A subset of Spec# • Language-agnostic way to express coding assumptions • Checked documentation of your API – Improved testability – Static verification – API documentation
  • 9. Requirements • .NET 4.0/4.5 • Visual Studio 2010/2012 – Any edition except “Express” edition • Download and install from Microsoft Research – http://research.microsoft.com/en-us/projects/contracts/ • Allowed for commercial use • In addition – Support exists for .NET 3.5 and VS 2008 as well – Contracts API is part of an external assembly
  • 10. Preconditions • Define what your API expects – Parameter validation – Object state – Environment condition – Anything the caller can check!
  • 11. Postconditions • Define what the caller can expect from your API – Return value constraints – Exception constraints – Object state after call
  • 12. Invariants • Define the rules which govern your object’s behavior – Object state – Field & property values – Things that always hold true
  • 13. Enough Talking. Show Me the Code!
  • 14. Should I Use It? It Depends… • Pros – Reduce bugs – Static verification – API documentation – Improved testability – Shallow learning curve • Cons – Experimental project – Static verifier less than perfect – Some issues with VS2012 – Compilation time increase
  • 15. There is a Middle Way! public class MyClass { public void SomeMethod(string s, int i) { if (s == null) throw new ArgumentNullException( "s", "Your input string cannot be null!"); if (i < 0) throw new ArgumentException( "Your input must be non-negative!", "i"); Contract.EndContractBlock(); // Your code here } }
  • 16. How Can I Choose? From the User Manual
  • 17. Code Contracts Internals • Contract Rewriter – ccrewrite • Static Verifier – cccheck • API Documentation – ccdoc • Ships with contract assemblies for many BCL types & methods
  • 19. Code Contracts Editor Extension • Visual Studio 2010 Only – 2012 support still pending – http://tinyurl.com/CCEditorExtensions • Has some stability issues
  • 20. Summary • A contract is more than an Interface • Design by Contract is a design approach • Code Contracts enables Design by Contract on .NET – Preconditions, Postconditions & Invariants • An experimental project from Microsoft Research • Rewrites your application’s IL code • Integrates with Editor Extensions & Pex • Give it a try!
  • 21. Resources • My Blog – http://stiller.co.il/blog • Code Contracts – http://research.microsoft.com/en-us/projects/contracts/ – http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf – http://social.msdn.microsoft.com/Forums/en-US/codecontracts/threads • Design by Contract – http://en.wikipedia.org/wiki/Design_by_contract • Pex – http://research.microsoft.com/en-us/projects/pex/
  • 22. Presenter contact details c: +972-54-6160646 e: erans@codevalue.net b: stiller.co.il/blog w: www.codevalue.net

Notas del editor

  1. Ask the crowd what do they think is the contract
  2. Coined by Bertrand Meyer – the creator of Eiffel