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

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Kürzlich hochgeladen (20)

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

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.