SlideShare a Scribd company logo
1 of 32
.NET 4.0 
Code Contracts 
KOEN METSU
Presentation provided by 
Koen Metsu 
◦ Independent .NET consultant 
◦ Blog: http://www.koenmetsu.com 
◦ Twitter: @koenmetsu
Agenda 
Introduction 
Basic concepts 
Code Contracts at work 
◦ Static checking 
◦ Runtime checking 
Advanced usage 
◦ Contract inheritance 
◦ Customize contract runtime 
◦ PEX 
◦ Documentation Generation 
◦ Contract reference assembly 
Future 
Resources
Maintaining proper internal 
state 
Provider exposes ITrainScheduler 
public interface ITrainScheduler 
{ 
IList<Train> GetScheduledTrains(DateTime start, DateTime end); 
void ScheduleTrain(string name, Route route); 
} 
As consumer 
◦ Range of dates? 
◦ Is there a max resultset? 
◦ Can I provide an empty train name? 
As provider 
◦ Raise exceptions on invalid input? 
◦ Debug.Assert to check internal state? 
◦ Reusability??
Code Contracts to the rescue! 
1 language agnostic API 
◦ same API for C#, VB.NET, F#, … 
◦ System.Diagnostics.Contracts 
◦ mscorlib 
Design By Contract 
◦ Define expectations from caller 
◦ Make promises 
◦ Maintain constant proper internal state 
Benefits: 
◦ Testing (e.g. Pex) 
◦ Documentation (e.g. SandCastle) 
◦ Static checking 
◦ Runtime checking
Very Basic concepts 
Object 
◦ State 
◦ Behavior 
Example: Dog 
◦ State 
◦ Age 
◦ Name 
◦ Color 
◦ Behavior 
◦ Bark 
◦ Sit 
◦ Drool
Basic Concepts 
Types of Contracts
Contracts in real life 
CUSTOMER 
1) I want that new monitor 
BIG MEDIASTORE EMPLOYEE 
2) That’ll be 200€ please! 
3) Thank you, your monitor will: 
◦ Have a remote 
◦ Be brand new
Preconditions before Code 
Contracts 
Validating input parameters 
◦ If … throw ArgumentException 
◦ Lots of documentation 
◦ Caller doesn’t know about valid input
Preconditions with Code 
Contracts 
Validating input 
◦ Validates state on method entry 
◦ Burden on caller, so must be about state visible to caller 
Contract.Requires(!string.IsNullOrEmpty(text)); 
Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(text)); 
Legacy code 
◦ Existing “If … then throw” can be integrated 
◦ Contract.EndContractBlock();
Making promises 
Postconditions 
◦ Validates state on method exit 
◦ Helper methods in Contracts assembly 
◦ Result<T> 
◦ OldValue<T> 
◦ ValueAtReturn<T> 
Contract.Ensures(trainCount >5); 
Contract.Ensures(Contract.Result<Train>()!= null);
Maintaining proper state 
Object Invariants 
◦ Condition that holds at all (visible) time. 
◦ On public method exits 
[ContractInvariantMethod] 
private void SomeMeaningfulName() 
{ 
Contract.Invariant(CheckValidity()); 
}
Purity 
All contract checks must have no visible side-effects to callers 
Declare purity with [Pure] on 
◦ Types 
◦ Methods 
Considered pure 
◦ Implicit 
◦ Property getters 
◦ Operators 
◦ Methods of immutable types 
◦ Explicit 
◦ Methods/Types declared pure 
[Pure] 
private bool CheckValidity(string text) 
{ 
//logic here 
}
Quantifiers 
ForAll 
◦ Condition must hold for all elements 
Contract.Requires(Contract.ForAll(myEnumerable, x => x.IsValid)); 
Exists 
◦ Condition must hold for at least one element 
Contract.Requires(Contract.Exists(myEnumerable, x => x.IsChosen));
Asserting your state 
Assert 
◦ Condition must be valid 
Contract.Assert(myValue == expectedValue); 
Assume 
◦ Runtime checker 
◦ same as Contract.Assert 
◦ Static checker 
◦ Condition doesn’t have to be proven, it’s assumed to be true 
Contract.Assume(myValue == expectedValue);
Debug.Assert vs 
Contract.Assert 
Debug.Assert 
◦ Only in Debug builds 
◦ No tools 
◦ Works even with Code Contracts disabled 
Contract.Assert 
◦ Can work in release builds (configurable) 
◦ Tools 
◦ Does not work with Code Contracts disabled
Code Contracts at 
work
Upon installation 
New property pane
Static Checking 
Finds contract breaches before running 
Can run in background 
◦ Shows warnings for 
◦ Unproven contracts 
◦ Possible null references 
◦ Possible out of bounds calls 
◦ Redundant assumptions 
◦ Implicit arithmetic obligations
Working with the static 
checker 
Can be overwhelming 
Fix warnings 
◦ Statistically provable 
◦ Preconditions 
◦ Postconditions 
◦ Invariants 
◦ Assumptions & Assertions 
Baseline 
◦ Exclude current warnings 
◦ Export to file
Runtime Checking 
On Failure: 
◦ Throw ContractException 
◦ Internal class 
◦ “not catchable”… 
◦ … except by catching general exception 
◦ Assert on Failure 
REMINDER: BEST PRACTICE 
DO NOT CATCH GENERAL EXCEPTION
CCRewrite 
CCRewrite
Advanced Usage
Contract Inheritance 
Interface does not show you the behavior 
Contracts are inherited 
◦ Preconditions 
◦ Can’t add extra ( Liskov Substition Principle ) 
◦ Postconditions & Invariants 
◦ Can be made stronger 
Making your interfaces/abstracts behave 
[ContractClass(typeof(IFooContract))] 
Dummy class, implementing interface 
◦ Contracts in method body 
[ContractClassFor(typeof(IFooContract))]
Usage in an existing project 
Enable the baseline 
◦ Stores all warnings during next run in an Xml file 
◦ Warnings in the Xml file will not be shown again
Customize Contract Runtime 
Contract handling 
Contract failure 
Override Runtime Checking Behavior 
◦ Every Contract check 
◦ ReportFailure method 
◦ RaiseContractFailedEvent
Pex 
Automated White Box Testing 
◦ Parameterized Unit Tests 
◦ Analyzes code under test 
Analyzes Code Contracts 
◦ 100% Code Contracts test coverage 
◦ Tests target contract conditions 
Suggests missing contracts
Sandcastle 
MSDN style API documentation generation 
◦ XML comments 
◦ Enable XML documentation output 
CodePlex 
◦ Sandcastle 
◦ Sandcastle Helpfile Builder 
Includes contract documentation
Isolate Contracts in Seperate 
Assembly 
Option: generate a reference assembly 
Ship when needed 
◦ Limit product size 
◦ Debugging 
Generates <AssemblyName>.Contracts.dll
Future of Code Contracts 
Usage 
◦ Use it personally to document and test your code 
◦ Great for interdeveloper use 
Built-in support 
◦ .NET 4.0 BCL behavior defined by Code Contracts 
◦ Supported in Silverlight 4 
◦ VS add-in 
Third party tools supporting Code Contracts 
◦ PEX, Sandcastle, Resharper
Resources 
Code Contracts 
◦ Official site 
Pex 
◦ Official site 
◦ http://www.pexforfun.com 
Sandcastle 
◦ Official site 
◦ Sandcastle Helpfile Builder
Q&A 
Questions?

More Related Content

Viewers also liked

Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Binu Bhasuran
 
Advanced c#
Advanced c#Advanced c#
Advanced c#saranuru
 
Microsoft Managed Extensibility Framework
Microsoft Managed Extensibility FrameworkMicrosoft Managed Extensibility Framework
Microsoft Managed Extensibility FrameworkBinu Bhasuran
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLMohammad Shaker
 
Advanced C#. Part 1
Advanced C#. Part 1Advanced C#. Part 1
Advanced C#. Part 1eleksdev
 
Advanced C#. Part 2
Advanced C#. Part 2Advanced C#. Part 2
Advanced C#. Part 2eleksdev
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel ProgrammingAlex Moore
 
What’s new in Visual Studio 2012 & .NET 4.5
What’s new in Visual Studio 2012 & .NET 4.5What’s new in Visual Studio 2012 & .NET 4.5
What’s new in Visual Studio 2012 & .NET 4.5Robert MacLean
 
Patterns For Cloud Computing
Patterns For Cloud ComputingPatterns For Cloud Computing
Patterns For Cloud ComputingSimon Guest
 
Web Application Development Fundamentals
Web Application Development FundamentalsWeb Application Development Fundamentals
Web Application Development FundamentalsMohammed Makhlouf
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web ArchitectureChamnap Chhorn
 

Viewers also liked (16)

Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Microsoft Managed Extensibility Framework
Microsoft Managed Extensibility FrameworkMicrosoft Managed Extensibility Framework
Microsoft Managed Extensibility Framework
 
.Net 3.5
.Net 3.5.Net 3.5
.Net 3.5
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XML
 
Advanced C#. Part 1
Advanced C#. Part 1Advanced C#. Part 1
Advanced C#. Part 1
 
Advanced C#. Part 2
Advanced C#. Part 2Advanced C#. Part 2
Advanced C#. Part 2
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming
 
Cloud Computing
Cloud ComputingCloud Computing
Cloud Computing
 
What’s new in Visual Studio 2012 & .NET 4.5
What’s new in Visual Studio 2012 & .NET 4.5What’s new in Visual Studio 2012 & .NET 4.5
What’s new in Visual Studio 2012 & .NET 4.5
 
Patterns For Cloud Computing
Patterns For Cloud ComputingPatterns For Cloud Computing
Patterns For Cloud Computing
 
Cloud Computing
Cloud ComputingCloud Computing
Cloud Computing
 
SOA Unit I
SOA Unit ISOA Unit I
SOA Unit I
 
Web Application Development Fundamentals
Web Application Development FundamentalsWeb Application Development Fundamentals
Web Application Development Fundamentals
 
Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
 

Similar to .NET 4.0 Code Contracts (2010)

Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code ContractsRainer Stropek
 
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 -2013David McCarter
 
Rock Your Code with Code Contracts
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code ContractsDavid McCarter
 
Design by Contract | Code Contracts in C# .NET
Design by Contract | Code Contracts in C# .NETDesign by Contract | Code Contracts in C# .NET
Design by Contract | Code Contracts in C# .NETDariusz Wozniak
 
Contract-oriented PLSQL Programming
Contract-oriented PLSQL ProgrammingContract-oriented PLSQL Programming
Contract-oriented PLSQL ProgrammingJohn Beresniewicz
 
Learning Solidity
Learning SolidityLearning Solidity
Learning SolidityArnold Pham
 
MongoDB World 2018: Transactions and Durability: Putting the “D” in ACID
MongoDB World 2018: Transactions and Durability: Putting the “D” in ACIDMongoDB World 2018: Transactions and Durability: Putting the “D” in ACID
MongoDB World 2018: Transactions and Durability: Putting the “D” in ACIDMongoDB
 
curl security - curl up 2022
curl security - curl up 2022curl security - curl up 2022
curl security - curl up 2022Daniel Stenberg
 
Best practices to build secure smart contracts
Best practices to build secure smart contractsBest practices to build secure smart contracts
Best practices to build secure smart contractsGautam Anand
 
Code contracts by Dmytro Mindra
Code contracts by Dmytro MindraCode contracts by Dmytro Mindra
Code contracts by Dmytro MindraAlex Tumanoff
 
Introduction to service stack
Introduction to service stackIntroduction to service stack
Introduction to service stackFabio Cozzolino
 
Smart contracts using web3.js
Smart contracts using web3.jsSmart contracts using web3.js
Smart contracts using web3.jsFelix Crisan
 
Software quality with Code Contracts and PEX - CodeCamp16oct2010
Software quality with Code Contracts and PEX - CodeCamp16oct2010Software quality with Code Contracts and PEX - CodeCamp16oct2010
Software quality with Code Contracts and PEX - CodeCamp16oct2010Codecamp Romania
 
Blockchain technology-in-fin tech - Anton Sitnikov
Blockchain technology-in-fin tech - Anton SitnikovBlockchain technology-in-fin tech - Anton Sitnikov
Blockchain technology-in-fin tech - Anton SitnikovDataFest Tbilisi
 
Contract-based Testing Approach as a Tool for Shift Lef
Contract-based Testing Approach as a Tool for Shift LefContract-based Testing Approach as a Tool for Shift Lef
Contract-based Testing Approach as a Tool for Shift LefKatherine Golovinova
 

Similar to .NET 4.0 Code Contracts (2010) (20)

Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code Contracts
 
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
 
Rock Your Code with Code Contracts
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code Contracts
 
Design by Contract | Code Contracts in C# .NET
Design by Contract | Code Contracts in C# .NETDesign by Contract | Code Contracts in C# .NET
Design by Contract | Code Contracts in C# .NET
 
Contract-oriented PLSQL Programming
Contract-oriented PLSQL ProgrammingContract-oriented PLSQL Programming
Contract-oriented PLSQL Programming
 
Code Contracts API In .NET
Code Contracts API In .NETCode Contracts API In .NET
Code Contracts API In .NET
 
Learning Solidity
Learning SolidityLearning Solidity
Learning Solidity
 
MongoDB World 2018: Transactions and Durability: Putting the “D” in ACID
MongoDB World 2018: Transactions and Durability: Putting the “D” in ACIDMongoDB World 2018: Transactions and Durability: Putting the “D” in ACID
MongoDB World 2018: Transactions and Durability: Putting the “D” in ACID
 
Code Contracts API In .Net
Code Contracts API In .NetCode Contracts API In .Net
Code Contracts API In .Net
 
Azure functions
Azure functionsAzure functions
Azure functions
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
curl security - curl up 2022
curl security - curl up 2022curl security - curl up 2022
curl security - curl up 2022
 
Best practices to build secure smart contracts
Best practices to build secure smart contractsBest practices to build secure smart contracts
Best practices to build secure smart contracts
 
Code contracts by Dmytro Mindra
Code contracts by Dmytro MindraCode contracts by Dmytro Mindra
Code contracts by Dmytro Mindra
 
Rust Smart Contracts
Rust Smart ContractsRust Smart Contracts
Rust Smart Contracts
 
Introduction to service stack
Introduction to service stackIntroduction to service stack
Introduction to service stack
 
Smart contracts using web3.js
Smart contracts using web3.jsSmart contracts using web3.js
Smart contracts using web3.js
 
Software quality with Code Contracts and PEX - CodeCamp16oct2010
Software quality with Code Contracts and PEX - CodeCamp16oct2010Software quality with Code Contracts and PEX - CodeCamp16oct2010
Software quality with Code Contracts and PEX - CodeCamp16oct2010
 
Blockchain technology-in-fin tech - Anton Sitnikov
Blockchain technology-in-fin tech - Anton SitnikovBlockchain technology-in-fin tech - Anton Sitnikov
Blockchain technology-in-fin tech - Anton Sitnikov
 
Contract-based Testing Approach as a Tool for Shift Lef
Contract-based Testing Approach as a Tool for Shift LefContract-based Testing Approach as a Tool for Shift Lef
Contract-based Testing Approach as a Tool for Shift Lef
 

Recently uploaded

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 

Recently uploaded (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 

.NET 4.0 Code Contracts (2010)

  • 1. .NET 4.0 Code Contracts KOEN METSU
  • 2. Presentation provided by Koen Metsu ◦ Independent .NET consultant ◦ Blog: http://www.koenmetsu.com ◦ Twitter: @koenmetsu
  • 3. Agenda Introduction Basic concepts Code Contracts at work ◦ Static checking ◦ Runtime checking Advanced usage ◦ Contract inheritance ◦ Customize contract runtime ◦ PEX ◦ Documentation Generation ◦ Contract reference assembly Future Resources
  • 4. Maintaining proper internal state Provider exposes ITrainScheduler public interface ITrainScheduler { IList<Train> GetScheduledTrains(DateTime start, DateTime end); void ScheduleTrain(string name, Route route); } As consumer ◦ Range of dates? ◦ Is there a max resultset? ◦ Can I provide an empty train name? As provider ◦ Raise exceptions on invalid input? ◦ Debug.Assert to check internal state? ◦ Reusability??
  • 5. Code Contracts to the rescue! 1 language agnostic API ◦ same API for C#, VB.NET, F#, … ◦ System.Diagnostics.Contracts ◦ mscorlib Design By Contract ◦ Define expectations from caller ◦ Make promises ◦ Maintain constant proper internal state Benefits: ◦ Testing (e.g. Pex) ◦ Documentation (e.g. SandCastle) ◦ Static checking ◦ Runtime checking
  • 6. Very Basic concepts Object ◦ State ◦ Behavior Example: Dog ◦ State ◦ Age ◦ Name ◦ Color ◦ Behavior ◦ Bark ◦ Sit ◦ Drool
  • 7. Basic Concepts Types of Contracts
  • 8. Contracts in real life CUSTOMER 1) I want that new monitor BIG MEDIASTORE EMPLOYEE 2) That’ll be 200€ please! 3) Thank you, your monitor will: ◦ Have a remote ◦ Be brand new
  • 9. Preconditions before Code Contracts Validating input parameters ◦ If … throw ArgumentException ◦ Lots of documentation ◦ Caller doesn’t know about valid input
  • 10. Preconditions with Code Contracts Validating input ◦ Validates state on method entry ◦ Burden on caller, so must be about state visible to caller Contract.Requires(!string.IsNullOrEmpty(text)); Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(text)); Legacy code ◦ Existing “If … then throw” can be integrated ◦ Contract.EndContractBlock();
  • 11. Making promises Postconditions ◦ Validates state on method exit ◦ Helper methods in Contracts assembly ◦ Result<T> ◦ OldValue<T> ◦ ValueAtReturn<T> Contract.Ensures(trainCount >5); Contract.Ensures(Contract.Result<Train>()!= null);
  • 12. Maintaining proper state Object Invariants ◦ Condition that holds at all (visible) time. ◦ On public method exits [ContractInvariantMethod] private void SomeMeaningfulName() { Contract.Invariant(CheckValidity()); }
  • 13. Purity All contract checks must have no visible side-effects to callers Declare purity with [Pure] on ◦ Types ◦ Methods Considered pure ◦ Implicit ◦ Property getters ◦ Operators ◦ Methods of immutable types ◦ Explicit ◦ Methods/Types declared pure [Pure] private bool CheckValidity(string text) { //logic here }
  • 14. Quantifiers ForAll ◦ Condition must hold for all elements Contract.Requires(Contract.ForAll(myEnumerable, x => x.IsValid)); Exists ◦ Condition must hold for at least one element Contract.Requires(Contract.Exists(myEnumerable, x => x.IsChosen));
  • 15. Asserting your state Assert ◦ Condition must be valid Contract.Assert(myValue == expectedValue); Assume ◦ Runtime checker ◦ same as Contract.Assert ◦ Static checker ◦ Condition doesn’t have to be proven, it’s assumed to be true Contract.Assume(myValue == expectedValue);
  • 16. Debug.Assert vs Contract.Assert Debug.Assert ◦ Only in Debug builds ◦ No tools ◦ Works even with Code Contracts disabled Contract.Assert ◦ Can work in release builds (configurable) ◦ Tools ◦ Does not work with Code Contracts disabled
  • 18. Upon installation New property pane
  • 19. Static Checking Finds contract breaches before running Can run in background ◦ Shows warnings for ◦ Unproven contracts ◦ Possible null references ◦ Possible out of bounds calls ◦ Redundant assumptions ◦ Implicit arithmetic obligations
  • 20. Working with the static checker Can be overwhelming Fix warnings ◦ Statistically provable ◦ Preconditions ◦ Postconditions ◦ Invariants ◦ Assumptions & Assertions Baseline ◦ Exclude current warnings ◦ Export to file
  • 21. Runtime Checking On Failure: ◦ Throw ContractException ◦ Internal class ◦ “not catchable”… ◦ … except by catching general exception ◦ Assert on Failure REMINDER: BEST PRACTICE DO NOT CATCH GENERAL EXCEPTION
  • 24. Contract Inheritance Interface does not show you the behavior Contracts are inherited ◦ Preconditions ◦ Can’t add extra ( Liskov Substition Principle ) ◦ Postconditions & Invariants ◦ Can be made stronger Making your interfaces/abstracts behave [ContractClass(typeof(IFooContract))] Dummy class, implementing interface ◦ Contracts in method body [ContractClassFor(typeof(IFooContract))]
  • 25. Usage in an existing project Enable the baseline ◦ Stores all warnings during next run in an Xml file ◦ Warnings in the Xml file will not be shown again
  • 26. Customize Contract Runtime Contract handling Contract failure Override Runtime Checking Behavior ◦ Every Contract check ◦ ReportFailure method ◦ RaiseContractFailedEvent
  • 27. Pex Automated White Box Testing ◦ Parameterized Unit Tests ◦ Analyzes code under test Analyzes Code Contracts ◦ 100% Code Contracts test coverage ◦ Tests target contract conditions Suggests missing contracts
  • 28. Sandcastle MSDN style API documentation generation ◦ XML comments ◦ Enable XML documentation output CodePlex ◦ Sandcastle ◦ Sandcastle Helpfile Builder Includes contract documentation
  • 29. Isolate Contracts in Seperate Assembly Option: generate a reference assembly Ship when needed ◦ Limit product size ◦ Debugging Generates <AssemblyName>.Contracts.dll
  • 30. Future of Code Contracts Usage ◦ Use it personally to document and test your code ◦ Great for interdeveloper use Built-in support ◦ .NET 4.0 BCL behavior defined by Code Contracts ◦ Supported in Silverlight 4 ◦ VS add-in Third party tools supporting Code Contracts ◦ PEX, Sandcastle, Resharper
  • 31. Resources Code Contracts ◦ Official site Pex ◦ Official site ◦ http://www.pexforfun.com Sandcastle ◦ Official site ◦ Sandcastle Helpfile Builder

Editor's Notes

  1. Expectations for Interfaces vsClasses .NET interface’s don’t contain implementation details. But, isn’t the fact that a particular method’s argument and return value should never ever be null a concern of the interface definition and not the classes that implement it?
  2. Code Contracts are checked in this sequence
  3. CODESAMPLE: Show if … throw argumentexception Take note of the amount of documentation. ( this is a public api you’re writing )
  4. Code Sample
  5. CODE SAMPLE: - show how to write postcondition - Put emphasis on validating your own code Worden in begin method geplaatst, check gebeurt wel degelijk op einde Hoewel preconditions ( validating input ) gemakkelijk te implementeren is zonder Code Contracts, zijn postconditions moeilijker: oorspronkelijke waarden zelf bijhouden, wat bij foutieve staat, … All preconditions and postconditions are expressed before the main implementation in Code Contracts. The tools assume that anything that comes after the last reference to Contract (apart from calls to Assert and Assume, which we'll meet in a minute) is part of the implementation, but anything up to that point is purely contractual and has no impact on the real work of the method. If you mistakenly put a postcondition at the end of the method, Code Contracts will complain of a "malformed contract."
  6. Invariants are contracts about the state of the object which should apply at all times that the state is visible. In other words, it's okay to change an invariant while a public method in the class is running, but at the end of the method the invariant should satisfied again.
  7. Purity will be checked in the future
  8. Contract.Assert versus Debug.Assert -    Release build kan Contract.Asserts bevatten (geen Debug.Asserts) -    Static / Runtime checker zoekt naar Contract.Asserts, niet naar Debug.Asserts -    Als Contracts disabled zijn, worden Debug.Asserts (in debug builds) wel nog uitgevoerd
  9. Up until now, Code Contracts did not do anything. We just declared them, but as such, they do nothing. It’s only with the Code Contract tools they actually do anything besides documenting your code.
  10. Demo Static checking
  11. Demo Code Contracts property pane Demo Runtime checking
  12. DEMO
  13. DEMO
  14. DEMO Wat images om de boel op te vrolijken
  15. Uitleg over met welke opties je best kan deployen