SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Code Contracts
Mini-Training

01/2014
Agenda
What is this?
Are they different from Unit-Tests?
How that works?
When should we use them?
Going further…

2
What is this?
• Design by Contract has been invented by B. Meyer in 1986 when
he specified the Eiffel language
• The principle is to specify what must be true at some point in the
execution of a program
• In many programming languages, contracts are implemented with
assert
• Assertions represent a contract specifying the responsibilities
between the customer and the provider in a piece of code

• Design by contract does not replace regular testing strategies…
we’ll see that later.
3
What is this?
• Code Contracts is a coding practice
• A contract is an assertion in the code
• Contracts take the form of preconditions, postconditions, and
object invariants (a condition which is always true)
• Contracts are expressed using static method calls at method
entries
• A contract is a form of documentation
• Runtime checking
• Works well with static analyzer tool like Resharper ;-)
But remember…
• A contract is not a behavior!
4
Are they different from Unit-Tests?
Not really 
As Patrick Smacchia said: “Code Contracts and Automated Testing
are pretty much the same thing”
– They check often for code behavior correctness
– They trigger obvious failure in case of broken correctness found
– They document code behavior

Code Contracts assertions raise obvious failure when violated during
the execution of some automated tests
When using massively contracts and unit-tests, maintenance cost is
cut by an order of magnitude
5
Are they different from Unit-Tests?
Contracts are not a replacement for Tests and vice-versa: both should
be practiced seriously:
• Contracts need Automated Tests to be exercised often in a
repeatable way.
• Automated Tests need Contracts as a much finer way to check
code behavior correctness, inside the code itself.

Chances that a bug remains undetected are pretty close to 0 when
the code is both 100% covered by tests and contains an optimal set
of contract assertions.
Read full Patrick Smacchia article.

6
How that works?
In .Net, there’s 2 way to do it:
• Microsoft Code Contracts Framework
• System.Diagnostics Debug.Assert()

7
When should we use them?
Contracts in C# are more than 60% about avoiding
NullReferenceException but there are other situations when it’s cool to
do so:
–
–
–
–
–

str.Length > 2
str[0] == ‘.’
i > 10
validate an invariant state inside a loop
…

But as Patrick Smacchia says: remember that null reference check
represent like half of the bugs on earth! (aka the Billion $ mistake)
8
When should we use them?
Code Contract vs. Debug.Assert()?
Code Contract is a really nice framework that allows you a lot of things
(contract on interfaces members, Require(), Ensure(), Invariant(),
ValueAtReturn(), …)
But it doubles compilation time! Code Contracts assemblies get
rewritten once compiled by the C#. (but it might change in C# 6!)

9
When should we use them?
In practice use contracts on the public surface API of your application and
Debug.Assert() everywhere else!
Stephen Cleary suggests that:
Set this on your Release project properties (code contracts tab)

This will output an “<applicationName>.Contracts.dll
That way: Projects consuming your library should reference your Release build. In
their Debug configuration, they should check "Perform Runtime Contract Checking"
and "Call-site Requires Checking"; this will ensure that the code contracts for your
library's public API are enforced at runtime (the "Call-site" option uses the
".Contracts.dll" assembly that you built). In their Release configuration, they should
leave code contracts disabled, which allows all assemblies to run at full speed.
10
Give a try to…

http://pexforfun.com/default.aspx?language=CSharp&sample=StringTrimSuffix

11
Give a try to…
• Microsoft Code Digger
– analyzes possible execution paths
through your .NET code. The result
is a table where each row shows a
unique behavior of your code. The
table helps you understand the
behavior of the code, and it may
also uncover hidden bugs.

• Code Contracts Editor Extensions
– provides
contract
support
programmers as they edit code

for

12
Questions?

13
Some links…
Design by contract on Wikipedia
Code Contracts @Microsoft
Code Contracts User Manual (pdf)
Code Contracts is the next coding practice you should learn and use

Better Than Unit Tests (to go further with other test techniques, a bit off-topic but worth a read)
Patrick Smacchia (NDepend) @Twitter
Michael Nygard @ThinkRelevance & @Twitter
Code Contracts for .NET VisualStudio Gallery
Pretty interesting question on SO and nice answer by Jon Skeet himself!
Simple and Easy Code Contracts - Stephen Cleary’s guide to get started with some useful information
about build settings

14
Find out more
• On https://techblog.betclicgroup.com/

•

@__MaxS__
About Betclic
•

•

•

Betclic Everest Group, one of the world leaders in online gaming, has a unique portfolio
comprising various complementary international brands: Betclic, Everest Gaming, bet-athome.com, Expekt…
Active in 100 countries with more than 12 million customers worldwide, the Group is
committed to promoting secure and responsible gaming and is a member of several
international professional associations including the EGBA (European Gaming and Betting
Association) and the ESSA (European Sports Security Association).
Through our brands, Betclic Everest Group places expertise, technological know-how and
security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion
of our players.

Weitere ähnliche Inhalte

Mehr von Betclic Everest Group Tech Team

Mini-training: Personalization & Recommendation Demystified
Mini-training: Personalization & Recommendation DemystifiedMini-training: Personalization & Recommendation Demystified
Mini-training: Personalization & Recommendation DemystifiedBetclic Everest Group Tech Team
 

Mehr von Betclic Everest Group Tech Team (20)

Mini training - Moving to xUnit.net
Mini training - Moving to xUnit.netMini training - Moving to xUnit.net
Mini training - Moving to xUnit.net
 
Mini training - Introduction to Microsoft Azure Storage
Mini training - Introduction to Microsoft Azure StorageMini training - Introduction to Microsoft Azure Storage
Mini training - Introduction to Microsoft Azure Storage
 
Akka.Net
Akka.NetAkka.Net
Akka.Net
 
Mini training- Scenario Driven Design
Mini training- Scenario Driven DesignMini training- Scenario Driven Design
Mini training- Scenario Driven Design
 
Email Management in Outlook
Email Management in OutlookEmail Management in Outlook
Email Management in Outlook
 
Mini-Training: SSO with Windows Identity Foundation
Mini-Training: SSO with Windows Identity FoundationMini-Training: SSO with Windows Identity Foundation
Mini-Training: SSO with Windows Identity Foundation
 
Training - What is Performance ?
Training  - What is Performance ?Training  - What is Performance ?
Training - What is Performance ?
 
Mini-Training: Docker
Mini-Training: DockerMini-Training: Docker
Mini-Training: Docker
 
Mini Training Flyway
Mini Training FlywayMini Training Flyway
Mini Training Flyway
 
Mini-Training: NDepend
Mini-Training: NDependMini-Training: NDepend
Mini-Training: NDepend
 
Management 3.0 Workout
Management 3.0 WorkoutManagement 3.0 Workout
Management 3.0 Workout
 
Lean for Business
Lean for BusinessLean for Business
Lean for Business
 
Short-Training asp.net vNext
Short-Training asp.net vNextShort-Training asp.net vNext
Short-Training asp.net vNext
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
Mini-Training: Mobile UX Trends
Mini-Training: Mobile UX TrendsMini-Training: Mobile UX Trends
Mini-Training: Mobile UX Trends
 
Training: MVVM Pattern
Training: MVVM PatternTraining: MVVM Pattern
Training: MVVM Pattern
 
Mini-training: Personalization & Recommendation Demystified
Mini-training: Personalization & Recommendation DemystifiedMini-training: Personalization & Recommendation Demystified
Mini-training: Personalization & Recommendation Demystified
 
Mini-training: Let’s Git It!
Mini-training: Let’s Git It!Mini-training: Let’s Git It!
Mini-training: Let’s Git It!
 
AngularJS Best Practices
AngularJS Best PracticesAngularJS Best Practices
AngularJS Best Practices
 
Mini-Training: Roslyn
Mini-Training: RoslynMini-Training: Roslyn
Mini-Training: Roslyn
 

Kürzlich hochgeladen

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Kürzlich hochgeladen (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Mini-training: Code Contract

  • 2. Agenda What is this? Are they different from Unit-Tests? How that works? When should we use them? Going further… 2
  • 3. What is this? • Design by Contract has been invented by B. Meyer in 1986 when he specified the Eiffel language • The principle is to specify what must be true at some point in the execution of a program • In many programming languages, contracts are implemented with assert • Assertions represent a contract specifying the responsibilities between the customer and the provider in a piece of code • Design by contract does not replace regular testing strategies… we’ll see that later. 3
  • 4. What is this? • Code Contracts is a coding practice • A contract is an assertion in the code • Contracts take the form of preconditions, postconditions, and object invariants (a condition which is always true) • Contracts are expressed using static method calls at method entries • A contract is a form of documentation • Runtime checking • Works well with static analyzer tool like Resharper ;-) But remember… • A contract is not a behavior! 4
  • 5. Are they different from Unit-Tests? Not really  As Patrick Smacchia said: “Code Contracts and Automated Testing are pretty much the same thing” – They check often for code behavior correctness – They trigger obvious failure in case of broken correctness found – They document code behavior Code Contracts assertions raise obvious failure when violated during the execution of some automated tests When using massively contracts and unit-tests, maintenance cost is cut by an order of magnitude 5
  • 6. Are they different from Unit-Tests? Contracts are not a replacement for Tests and vice-versa: both should be practiced seriously: • Contracts need Automated Tests to be exercised often in a repeatable way. • Automated Tests need Contracts as a much finer way to check code behavior correctness, inside the code itself. Chances that a bug remains undetected are pretty close to 0 when the code is both 100% covered by tests and contains an optimal set of contract assertions. Read full Patrick Smacchia article. 6
  • 7. How that works? In .Net, there’s 2 way to do it: • Microsoft Code Contracts Framework • System.Diagnostics Debug.Assert() 7
  • 8. When should we use them? Contracts in C# are more than 60% about avoiding NullReferenceException but there are other situations when it’s cool to do so: – – – – – str.Length > 2 str[0] == ‘.’ i > 10 validate an invariant state inside a loop … But as Patrick Smacchia says: remember that null reference check represent like half of the bugs on earth! (aka the Billion $ mistake) 8
  • 9. When should we use them? Code Contract vs. Debug.Assert()? Code Contract is a really nice framework that allows you a lot of things (contract on interfaces members, Require(), Ensure(), Invariant(), ValueAtReturn(), …) But it doubles compilation time! Code Contracts assemblies get rewritten once compiled by the C#. (but it might change in C# 6!) 9
  • 10. When should we use them? In practice use contracts on the public surface API of your application and Debug.Assert() everywhere else! Stephen Cleary suggests that: Set this on your Release project properties (code contracts tab) This will output an “<applicationName>.Contracts.dll That way: Projects consuming your library should reference your Release build. In their Debug configuration, they should check "Perform Runtime Contract Checking" and "Call-site Requires Checking"; this will ensure that the code contracts for your library's public API are enforced at runtime (the "Call-site" option uses the ".Contracts.dll" assembly that you built). In their Release configuration, they should leave code contracts disabled, which allows all assemblies to run at full speed. 10
  • 11. Give a try to… http://pexforfun.com/default.aspx?language=CSharp&sample=StringTrimSuffix 11
  • 12. Give a try to… • Microsoft Code Digger – analyzes possible execution paths through your .NET code. The result is a table where each row shows a unique behavior of your code. The table helps you understand the behavior of the code, and it may also uncover hidden bugs. • Code Contracts Editor Extensions – provides contract support programmers as they edit code for 12
  • 14. Some links… Design by contract on Wikipedia Code Contracts @Microsoft Code Contracts User Manual (pdf) Code Contracts is the next coding practice you should learn and use Better Than Unit Tests (to go further with other test techniques, a bit off-topic but worth a read) Patrick Smacchia (NDepend) @Twitter Michael Nygard @ThinkRelevance & @Twitter Code Contracts for .NET VisualStudio Gallery Pretty interesting question on SO and nice answer by Jon Skeet himself! Simple and Easy Code Contracts - Stephen Cleary’s guide to get started with some useful information about build settings 14
  • 15. Find out more • On https://techblog.betclicgroup.com/ • @__MaxS__
  • 16. About Betclic • • • Betclic Everest Group, one of the world leaders in online gaming, has a unique portfolio comprising various complementary international brands: Betclic, Everest Gaming, bet-athome.com, Expekt… Active in 100 countries with more than 12 million customers worldwide, the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association). Through our brands, Betclic Everest Group places expertise, technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players.