SlideShare a Scribd company logo
1 of 31
DESIGN BY
CONTRACT
WITH CODE CONTRACTS
CONFESSION :(
Confession :(

“How many of you
do write unit tests?”
Confession :(

“How many of you do
write documentation?”
Confession :(

“How many of you do
write asserts?”
JUSTIFICATION :)
Justification :)
THE GOOD PART

“At some extent all of these
tools don`t work in a real life.”
- me
Justification :)
WATCH OUT

Documentation

No documentation is better
than bad documentation

CODE SNIPPET
//declare variable foo as an integer and
//set it to three.
private int foo = 3;
Justification :)
WATCH OUT
CODE SNIPPET

Unit tests

Are limited and time
consuming to
support

[Test]
public void PressEquals_AddingTwoPlusTwo_ReturnsFour()
{
// Arrange
decimal value1 = 2m;
decimal value2 = 2m;
decimal expected = 4m;
var calculator = new Calculator();
// Act
calculator.Enter(value1);
calculator.PressPlus();
calculator.Enter(value2);
calculator.PressEquals();
decimal actual = calculator.Display;
// Assert
Assert.AreEqual(expected, actual,
"When adding {0} + {1}, expected {2} but found
{3}.", value1, value2, expected, actual);
}
Justification :)
WATCH OUT
CODE SNIPPET
public string Substring(int startIndex, int length)

Asserts

Make little use for
calling code

CODE SNIPPET
public string Substring(int startIndex, int length)
{
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex");
if (startIndex > this.Length)
throw new ArgumentOutOfRangeException("startIndex");
if (length < 0)
throw new ArgumentOutOfRangeException("length");
if (startIndex > this.Length - length)
throw new ArgumentOutOfRangeException("length");
if (length == 0)
return string.Empty;
else
return this.InternalSubStringWithChecks(startIndex, length, false);
}
Consequences
ABANDONING

“If so, why wouldn`t I
abandon all this crap?”
Consequences
PROGRAMMING BY COINCIDENCE

“We should avoid programming by
coincidence - relying on luck and
accidental successes - in favor of
programming deliberately.”
- Dave Thomas
Design by Contract
WHAT IS IT?

“A way of designing software, which implies formal and precise
specifications for software components with pre-conditions,
post-conditions and invariants in source code itself.”

Bertrand Meyer
EIFFEL PL, 1986
Design by Contract
EIFFEL
CODE SNIPPET

Pre-conditions
Post-conditions

connect_to_server (server: SOCKET)
-- Connect to a server.
require
server /= Void and then server.address /= Void
do
server.connect
ensure
connected: server.is_connected
end

CODE SNIPPET
class

Invariants

DATE
invariant
valid_day: 1 <= day and day <= 31
valid_hour: 0 <= hour and hour <= 23
end
Design by Contract
RULES

Metaphor : Client, Supplier agree on a Contract

1
2
3

The supplier must provide a certain product
(obligation) and is entitled to expect that the client
has paid its fee (benefit).
The client must pay the fee (obligation) and is
entitled to get the product (benefit).
Both parties must satisfy certain obligations, such as
laws and regulations, applying to all contracts.
Design by Contract
WHY?

“What are the benefits?”
Discoverability of your
API

Improved testability

Runtime & Static
Checking

Automatic generation
of documentation
Design by Contract
IMPLEMENTATIONS FOR .NET

“Do we have similar concept in modern programming
languages? Lets ask Microsoft.”
Microsoft Research
Code Contracts
WHAT IS IT?

“Microsoft`s implementation of
Design by Contract for .NET.
Proposed back in 2008.”
Code Contracts
WHAT IS IT?
CODE SNIPPET

Pre-conditions

class WebService
{
private IWarehouse store;
public WebService(IWarehouse store)
{
Contract.Requires(store != null);
Contract.Ensures(this.store != null);

Post-conditions

this.store = store;
}
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.store != null);
}

Invariants
}
Code Contracts
COMPLETE API

“Mostly it is nice and easy, but
occasionally it can be mind
blowing.”
Code Contracts
COMPONENTS

CCRewrite

CCCheck

CCDocGen

Binary Rewriter

Static Checker

XML Doc Extender
Code Contracts
RUNTIME CHECKING
WebService.cs
public WebService(IWarehouse store) {
Contract.Requires(store != null);
Contract.Ensures(this.store != null);
this.store = store;

WebService.dll

IL from requires

}

csc/vbc/…
+
ccrewrite

IL from body

IL from ensures
Code Contracts
RUNTIME CHECKING (GENERAL CLIENTS)
WebService.cs
public WebService(IWarehouse store) {
Contract.Requires(store != null);
Contract.Ensures(this.store != null);
this.store = store;
}

WebService.dll

IL from requires
csc/vbc/…
+
ccrewrite

IL from body
Code Contracts
RUNTIME CHECKING (TRUSTED CLIENTS)
WebService.cs
public WebService(IWarehouse store) {
Contract.Requires(store != null);
Contract.Ensures(this.store != null);
this.store = store;
}

WebService.dll

csc/vbc/…

IL from body
Code Contracts
DOCUMENTATION GENERATION
WebService.xml
<member
name="M:PDC.WebService.#ctor(PDC.
IWarehouse)">
<summary>Constructs a new
instance for processing orders
against the specified
warehouse.</summary>
<param name="store">The warehouse
this instance is to use. </param>
</member>

WebService.xml

ccdocgen
WebService.Contracts.dll

IL from requires
IL from ensures

<member
name="M:PDC.WebService.#ctor(PDC.IWarehouse)">
<summary>Constructs a new instance for
processing orders against the specified
warehouse.</summary>
<param name="store">The warehouse this
instance is to use. </param>
<requires> store != null </requires>
<ensures> this.store != null </ensures>
</member>
Code Contracts
CONTRACT REFERENCE ASSEMBLIES

“Companion assemblies generated
at compile time and contain only
contract portion of types.”
Code Contracts
ANNOYANCES

1
2
3

Static analysis is usually slow

Tools are failing from time to time
No way to execute post-conditions under lock
statement
References
Code Contracts
http://msdn.microsoft.com/en-us/magazine/ee236408.aspx
Code Contracts on Microsoft Research
http://research.microsoft.com/en-us/projects/contracts/
Code Contracts on MSDN
http://msdn.microsoft.com/en-us/library/dd264808.aspx
Code Contracts in C#
http://www.infoq.com/articles/code-contracts-csharp
THANK YOU
Questions?

More Related Content

What's hot

Tech talk specflow_bddx_hassa_nagy
Tech talk specflow_bddx_hassa_nagyTech talk specflow_bddx_hassa_nagy
Tech talk specflow_bddx_hassa_nagySkills Matter
 
Journey to JavaScript (from C#)
Journey to JavaScript (from C#)Journey to JavaScript (from C#)
Journey to JavaScript (from C#)Ed Charbeneau
 
User story slicing exercise
User story slicing exerciseUser story slicing exercise
User story slicing exercisePaulo Clavijo
 
Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...
Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...
Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...Evgeniy Kuzmin
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builderMaurizio Vitale
 
Microservices. Test smarter, not harder. Voxxed Days 2019
Microservices. Test smarter, not harder. Voxxed Days 2019Microservices. Test smarter, not harder. Voxxed Days 2019
Microservices. Test smarter, not harder. Voxxed Days 2019Beth Skurrie
 
So What Do Cucumbers Have To Do With Testing
So What Do Cucumbers Have To Do With TestingSo What Do Cucumbers Have To Do With Testing
So What Do Cucumbers Have To Do With Testingsjmarsh
 
Consumer-driven contracts: avoid microservices integration hell! (LondonCD - ...
Consumer-driven contracts: avoid microservices integration hell! (LondonCD - ...Consumer-driven contracts: avoid microservices integration hell! (LondonCD - ...
Consumer-driven contracts: avoid microservices integration hell! (LondonCD - ...Pierre Vincent
 
Introduction to Behavior Driven Development
Introduction to Behavior Driven Development Introduction to Behavior Driven Development
Introduction to Behavior Driven Development Robin O'Brien
 
OpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideOpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideTim Burks
 
Bbp contract complete
Bbp contract completeBbp contract complete
Bbp contract completeAsha Panda
 

What's hot (12)

Tech talk specflow_bddx_hassa_nagy
Tech talk specflow_bddx_hassa_nagyTech talk specflow_bddx_hassa_nagy
Tech talk specflow_bddx_hassa_nagy
 
Journey to JavaScript (from C#)
Journey to JavaScript (from C#)Journey to JavaScript (from C#)
Journey to JavaScript (from C#)
 
User story slicing exercise
User story slicing exerciseUser story slicing exercise
User story slicing exercise
 
Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...
Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...
Contract testing. Isolated testing of microservices with pact.io - Evgeniy Ku...
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builder
 
Microservices. Test smarter, not harder. Voxxed Days 2019
Microservices. Test smarter, not harder. Voxxed Days 2019Microservices. Test smarter, not harder. Voxxed Days 2019
Microservices. Test smarter, not harder. Voxxed Days 2019
 
So What Do Cucumbers Have To Do With Testing
So What Do Cucumbers Have To Do With TestingSo What Do Cucumbers Have To Do With Testing
So What Do Cucumbers Have To Do With Testing
 
Google Guice
Google GuiceGoogle Guice
Google Guice
 
Consumer-driven contracts: avoid microservices integration hell! (LondonCD - ...
Consumer-driven contracts: avoid microservices integration hell! (LondonCD - ...Consumer-driven contracts: avoid microservices integration hell! (LondonCD - ...
Consumer-driven contracts: avoid microservices integration hell! (LondonCD - ...
 
Introduction to Behavior Driven Development
Introduction to Behavior Driven Development Introduction to Behavior Driven Development
Introduction to Behavior Driven Development
 
OpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideOpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-Side
 
Bbp contract complete
Bbp contract completeBbp contract complete
Bbp contract complete
 

Viewers also liked

13inmate project mkultra
13inmate project mkultra13inmate project mkultra
13inmate project mkultraLorenzo Dodi
 
Polymerase Chain Reaction
Polymerase Chain ReactionPolymerase Chain Reaction
Polymerase Chain Reactiona b
 
Year 1 pupils' presentations
Year 1 pupils' presentationsYear 1 pupils' presentations
Year 1 pupils' presentationslorcamollet
 
Webinar 'Could you transform the way you do R&D in just 5 years?' - May 2014
Webinar 'Could you transform the way you do R&D in just 5 years?' - May 2014Webinar 'Could you transform the way you do R&D in just 5 years?' - May 2014
Webinar 'Could you transform the way you do R&D in just 5 years?' - May 2014IDBS
 
Oceanspray &quot;Straight from the Bog&quot; Campaign analysis
Oceanspray &quot;Straight from the Bog&quot; Campaign analysisOceanspray &quot;Straight from the Bog&quot; Campaign analysis
Oceanspray &quot;Straight from the Bog&quot; Campaign analysisnichoe10
 
Biblia hebraica stuttgartensia
Biblia hebraica stuttgartensiaBiblia hebraica stuttgartensia
Biblia hebraica stuttgartensiagpelayomentor90
 
Ten words that makes you smile
Ten words that makes you smileTen words that makes you smile
Ten words that makes you smileJims Varkey
 
How to not freak out about common core
How to not freak out about common coreHow to not freak out about common core
How to not freak out about common coreGalesburg CUSD #205
 
день народного единства
день народного единствадень народного единства
день народного единстваkillaruns
 
Diseminare Curs Grundtvig, Malta 2012
Diseminare Curs Grundtvig, Malta 2012Diseminare Curs Grundtvig, Malta 2012
Diseminare Curs Grundtvig, Malta 2012Tamara Petrof
 
Inforica Corporate Presentation
Inforica Corporate PresentationInforica Corporate Presentation
Inforica Corporate PresentationSudeep DSouza
 
O net คณิตศาสตร์ 2552
O net คณิตศาสตร์ 2552O net คณิตศาสตร์ 2552
O net คณิตศาสตร์ 2552Justice MengKing
 
Refractometria joan l_ramos
Refractometria joan l_ramosRefractometria joan l_ramos
Refractometria joan l_ramosaula20_2012
 
портфолио Шликова В.В.
портфолио Шликова В.В.портфолио Шликова В.В.
портфолио Шликова В.В.TheShkola21
 
Project Development Brochure Hi Res
Project Development Brochure   Hi ResProject Development Brochure   Hi Res
Project Development Brochure Hi Resnevwebb
 

Viewers also liked (20)

13inmate project mkultra
13inmate project mkultra13inmate project mkultra
13inmate project mkultra
 
Polymerase Chain Reaction
Polymerase Chain ReactionPolymerase Chain Reaction
Polymerase Chain Reaction
 
Year 1 pupils' presentations
Year 1 pupils' presentationsYear 1 pupils' presentations
Year 1 pupils' presentations
 
Presentation 2
Presentation 2Presentation 2
Presentation 2
 
Dividers fbf
Dividers fbfDividers fbf
Dividers fbf
 
Bluetooth Low Energy y Moviles
Bluetooth Low Energy y MovilesBluetooth Low Energy y Moviles
Bluetooth Low Energy y Moviles
 
ศาสนาสากล
ศาสนาสากลศาสนาสากล
ศาสนาสากล
 
Webinar 'Could you transform the way you do R&D in just 5 years?' - May 2014
Webinar 'Could you transform the way you do R&D in just 5 years?' - May 2014Webinar 'Could you transform the way you do R&D in just 5 years?' - May 2014
Webinar 'Could you transform the way you do R&D in just 5 years?' - May 2014
 
Oceanspray &quot;Straight from the Bog&quot; Campaign analysis
Oceanspray &quot;Straight from the Bog&quot; Campaign analysisOceanspray &quot;Straight from the Bog&quot; Campaign analysis
Oceanspray &quot;Straight from the Bog&quot; Campaign analysis
 
Biblia hebraica stuttgartensia
Biblia hebraica stuttgartensiaBiblia hebraica stuttgartensia
Biblia hebraica stuttgartensia
 
Ten words that makes you smile
Ten words that makes you smileTen words that makes you smile
Ten words that makes you smile
 
How to not freak out about common core
How to not freak out about common coreHow to not freak out about common core
How to not freak out about common core
 
день народного единства
день народного единствадень народного единства
день народного единства
 
Diseminare Curs Grundtvig, Malta 2012
Diseminare Curs Grundtvig, Malta 2012Diseminare Curs Grundtvig, Malta 2012
Diseminare Curs Grundtvig, Malta 2012
 
Inforica Corporate Presentation
Inforica Corporate PresentationInforica Corporate Presentation
Inforica Corporate Presentation
 
O net คณิตศาสตร์ 2552
O net คณิตศาสตร์ 2552O net คณิตศาสตร์ 2552
O net คณิตศาสตร์ 2552
 
Refractometria joan l_ramos
Refractometria joan l_ramosRefractometria joan l_ramos
Refractometria joan l_ramos
 
портфолио Шликова В.В.
портфолио Шликова В.В.портфолио Шликова В.В.
портфолио Шликова В.В.
 
Mariana clavijo
Mariana clavijoMariana clavijo
Mariana clavijo
 
Project Development Brochure Hi Res
Project Development Brochure   Hi ResProject Development Brochure   Hi Res
Project Development Brochure Hi Res
 

Similar to Code Contracts

Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code ContractsRainer Stropek
 
Art of unit testing: how to do it right
Art of unit testing: how to do it rightArt of unit testing: how to do it right
Art of unit testing: how to do it rightDmytro Patserkovskyi
 
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
 
.NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010).NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010)Koen Metsu
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentEffective
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentJohn Blanco
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentEffectiveUI
 
Continuous Integration and Code Coverage in Xcode
Continuous Integration and Code Coverage in XcodeContinuous Integration and Code Coverage in Xcode
Continuous Integration and Code Coverage in XcodeHiep Luong
 
High Productivity Web Development Workflow
High Productivity Web Development WorkflowHigh Productivity Web Development Workflow
High Productivity Web Development WorkflowVũ Nguyễn
 
High productivity web development workflow - JavaScript Meetup Saigon 2014
High productivity web development workflow - JavaScript Meetup Saigon 2014High productivity web development workflow - JavaScript Meetup Saigon 2014
High productivity web development workflow - JavaScript Meetup Saigon 2014Oliver N
 
Rock Your Code with Code Contracts
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code ContractsDavid McCarter
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentguestc8093a6
 
WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...
WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...
WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...Amir Zmora
 
AWS Atlanta meetup Build Tools - Code Commit, Code Build, Code Deploy
AWS Atlanta meetup Build Tools - Code Commit, Code Build, Code DeployAWS Atlanta meetup Build Tools - Code Commit, Code Build, Code Deploy
AWS Atlanta meetup Build Tools - Code Commit, Code Build, Code DeployAdam Book
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your CodeNate Abele
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0Nate Abele
 
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 Code Contracts (20)

Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code Contracts
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Art of unit testing: how to do it right
Art of unit testing: how to do it rightArt of unit testing: how to do it right
Art of unit testing: how to do it right
 
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
 
.NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010).NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010)
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Continuous Integration and Code Coverage in Xcode
Continuous Integration and Code Coverage in XcodeContinuous Integration and Code Coverage in Xcode
Continuous Integration and Code Coverage in Xcode
 
AAA Automated Testing
AAA Automated TestingAAA Automated Testing
AAA Automated Testing
 
High Productivity Web Development Workflow
High Productivity Web Development WorkflowHigh Productivity Web Development Workflow
High Productivity Web Development Workflow
 
High productivity web development workflow - JavaScript Meetup Saigon 2014
High productivity web development workflow - JavaScript Meetup Saigon 2014High productivity web development workflow - JavaScript Meetup Saigon 2014
High productivity web development workflow - JavaScript Meetup Saigon 2014
 
Rock Your Code with Code Contracts
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code Contracts
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...
WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...
WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...
 
AWS Atlanta meetup Build Tools - Code Commit, Code Build, Code Deploy
AWS Atlanta meetup Build Tools - Code Commit, Code Build, Code DeployAWS Atlanta meetup Build Tools - Code Commit, Code Build, Code Deploy
AWS Atlanta meetup Build Tools - Code Commit, Code Build, Code Deploy
 
Coding Naked 2023
Coding Naked 2023Coding Naked 2023
Coding Naked 2023
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
 
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
 

More from Alexei Skachykhin

CSS Architecture: Writing Maintainable CSS
CSS Architecture: Writing Maintainable CSSCSS Architecture: Writing Maintainable CSS
CSS Architecture: Writing Maintainable CSSAlexei Skachykhin
 
Representational State Transfer
Representational State TransferRepresentational State Transfer
Representational State TransferAlexei Skachykhin
 
Web Real-time Communications
Web Real-time CommunicationsWeb Real-time Communications
Web Real-time CommunicationsAlexei Skachykhin
 
JavaScript as Development Platform
JavaScript as Development PlatformJavaScript as Development Platform
JavaScript as Development PlatformAlexei Skachykhin
 

More from Alexei Skachykhin (6)

CSS Architecture: Writing Maintainable CSS
CSS Architecture: Writing Maintainable CSSCSS Architecture: Writing Maintainable CSS
CSS Architecture: Writing Maintainable CSS
 
Representational State Transfer
Representational State TransferRepresentational State Transfer
Representational State Transfer
 
Web Real-time Communications
Web Real-time CommunicationsWeb Real-time Communications
Web Real-time Communications
 
JavaScript as Development Platform
JavaScript as Development PlatformJavaScript as Development Platform
JavaScript as Development Platform
 
HTML5 Comprehensive Guide
HTML5 Comprehensive GuideHTML5 Comprehensive Guide
HTML5 Comprehensive Guide
 
Windows 8
Windows 8Windows 8
Windows 8
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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
 

Recently uploaded (20)

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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...
 

Code Contracts

  • 3. Confession :( “How many of you do write unit tests?”
  • 4. Confession :( “How many of you do write documentation?”
  • 5. Confession :( “How many of you do write asserts?”
  • 7. Justification :) THE GOOD PART “At some extent all of these tools don`t work in a real life.” - me
  • 8. Justification :) WATCH OUT Documentation No documentation is better than bad documentation CODE SNIPPET //declare variable foo as an integer and //set it to three. private int foo = 3;
  • 9. Justification :) WATCH OUT CODE SNIPPET Unit tests Are limited and time consuming to support [Test] public void PressEquals_AddingTwoPlusTwo_ReturnsFour() { // Arrange decimal value1 = 2m; decimal value2 = 2m; decimal expected = 4m; var calculator = new Calculator(); // Act calculator.Enter(value1); calculator.PressPlus(); calculator.Enter(value2); calculator.PressEquals(); decimal actual = calculator.Display; // Assert Assert.AreEqual(expected, actual, "When adding {0} + {1}, expected {2} but found {3}.", value1, value2, expected, actual); }
  • 10. Justification :) WATCH OUT CODE SNIPPET public string Substring(int startIndex, int length) Asserts Make little use for calling code CODE SNIPPET public string Substring(int startIndex, int length) { if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex"); if (startIndex > this.Length) throw new ArgumentOutOfRangeException("startIndex"); if (length < 0) throw new ArgumentOutOfRangeException("length"); if (startIndex > this.Length - length) throw new ArgumentOutOfRangeException("length"); if (length == 0) return string.Empty; else return this.InternalSubStringWithChecks(startIndex, length, false); }
  • 11. Consequences ABANDONING “If so, why wouldn`t I abandon all this crap?”
  • 12. Consequences PROGRAMMING BY COINCIDENCE “We should avoid programming by coincidence - relying on luck and accidental successes - in favor of programming deliberately.” - Dave Thomas
  • 13. Design by Contract WHAT IS IT? “A way of designing software, which implies formal and precise specifications for software components with pre-conditions, post-conditions and invariants in source code itself.” Bertrand Meyer EIFFEL PL, 1986
  • 14. Design by Contract EIFFEL CODE SNIPPET Pre-conditions Post-conditions connect_to_server (server: SOCKET) -- Connect to a server. require server /= Void and then server.address /= Void do server.connect ensure connected: server.is_connected end CODE SNIPPET class Invariants DATE invariant valid_day: 1 <= day and day <= 31 valid_hour: 0 <= hour and hour <= 23 end
  • 15. Design by Contract RULES Metaphor : Client, Supplier agree on a Contract 1 2 3 The supplier must provide a certain product (obligation) and is entitled to expect that the client has paid its fee (benefit). The client must pay the fee (obligation) and is entitled to get the product (benefit). Both parties must satisfy certain obligations, such as laws and regulations, applying to all contracts.
  • 16. Design by Contract WHY? “What are the benefits?” Discoverability of your API Improved testability Runtime & Static Checking Automatic generation of documentation
  • 17. Design by Contract IMPLEMENTATIONS FOR .NET “Do we have similar concept in modern programming languages? Lets ask Microsoft.”
  • 18.
  • 20. Code Contracts WHAT IS IT? “Microsoft`s implementation of Design by Contract for .NET. Proposed back in 2008.”
  • 21. Code Contracts WHAT IS IT? CODE SNIPPET Pre-conditions class WebService { private IWarehouse store; public WebService(IWarehouse store) { Contract.Requires(store != null); Contract.Ensures(this.store != null); Post-conditions this.store = store; } [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(this.store != null); } Invariants }
  • 22. Code Contracts COMPLETE API “Mostly it is nice and easy, but occasionally it can be mind blowing.”
  • 24. Code Contracts RUNTIME CHECKING WebService.cs public WebService(IWarehouse store) { Contract.Requires(store != null); Contract.Ensures(this.store != null); this.store = store; WebService.dll IL from requires } csc/vbc/… + ccrewrite IL from body IL from ensures
  • 25. Code Contracts RUNTIME CHECKING (GENERAL CLIENTS) WebService.cs public WebService(IWarehouse store) { Contract.Requires(store != null); Contract.Ensures(this.store != null); this.store = store; } WebService.dll IL from requires csc/vbc/… + ccrewrite IL from body
  • 26. Code Contracts RUNTIME CHECKING (TRUSTED CLIENTS) WebService.cs public WebService(IWarehouse store) { Contract.Requires(store != null); Contract.Ensures(this.store != null); this.store = store; } WebService.dll csc/vbc/… IL from body
  • 27. Code Contracts DOCUMENTATION GENERATION WebService.xml <member name="M:PDC.WebService.#ctor(PDC. IWarehouse)"> <summary>Constructs a new instance for processing orders against the specified warehouse.</summary> <param name="store">The warehouse this instance is to use. </param> </member> WebService.xml ccdocgen WebService.Contracts.dll IL from requires IL from ensures <member name="M:PDC.WebService.#ctor(PDC.IWarehouse)"> <summary>Constructs a new instance for processing orders against the specified warehouse.</summary> <param name="store">The warehouse this instance is to use. </param> <requires> store != null </requires> <ensures> this.store != null </ensures> </member>
  • 28. Code Contracts CONTRACT REFERENCE ASSEMBLIES “Companion assemblies generated at compile time and contain only contract portion of types.”
  • 29. Code Contracts ANNOYANCES 1 2 3 Static analysis is usually slow Tools are failing from time to time No way to execute post-conditions under lock statement
  • 30. References Code Contracts http://msdn.microsoft.com/en-us/magazine/ee236408.aspx Code Contracts on Microsoft Research http://research.microsoft.com/en-us/projects/contracts/ Code Contracts on MSDN http://msdn.microsoft.com/en-us/library/dd264808.aspx Code Contracts in C# http://www.infoq.com/articles/code-contracts-csharp