SlideShare ist ein Scribd-Unternehmen logo
1 von 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?

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie Design by Contract with 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 DevelopmentEffectiveUI
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentJohn Blanco
 
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
 

Ähnlich wie Design by Contract with 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
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
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
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
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
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
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
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
 

Kürzlich hochgeladen (20)

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
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
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
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.
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
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
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
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
 

Design by Contract with 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