SlideShare a Scribd company logo
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.”
Code Contracts
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?
Ad

More Related Content

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
Skills 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 exercise
Paulo 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 builder
Maurizio 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 2019
Beth 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 Testing
sjmarsh
 
Google Guice
Google GuiceGoogle Guice
Google Guice
Andriy Andrunevchyn
 
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-Side
Tim Burks
 
Bbp contract complete
Bbp contract completeBbp contract complete
Bbp contract complete
Asha Panda
 
Tech talk specflow_bddx_hassa_nagy
Tech talk specflow_bddx_hassa_nagyTech talk specflow_bddx_hassa_nagy
Tech talk specflow_bddx_hassa_nagy
Skills 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 exercise
Paulo 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 builder
Maurizio 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 2019
Beth 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 Testing
sjmarsh
 
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-Side
Tim Burks
 
Bbp contract complete
Bbp contract completeBbp contract complete
Bbp contract complete
Asha Panda
 

Viewers also liked (20)

13inmate project mkultra
13inmate project mkultra13inmate project mkultra
13inmate project mkultra
Lorenzo Dodi
 
Polymerase Chain Reaction
Polymerase Chain ReactionPolymerase Chain Reaction
Polymerase Chain Reaction
a b
 
Year 1 pupils' presentations
Year 1 pupils' presentationsYear 1 pupils' presentations
Year 1 pupils' presentations
lorcamollet
 
Presentation 2
Presentation 2Presentation 2
Presentation 2
Christopher Mitchell
 
Bluetooth Low Energy y Moviles
Bluetooth Low Energy y MovilesBluetooth Low Energy y Moviles
Bluetooth Low Energy y Moviles
Ernesto Freyre Gonzalez
 
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
IDBS
 
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
nichoe10
 
Biblia hebraica stuttgartensia
Biblia hebraica stuttgartensiaBiblia hebraica stuttgartensia
Biblia hebraica stuttgartensia
gpelayomentor90
 
Ten words that makes you smile
Ten words that makes you smileTen words that makes you smile
Ten words that makes you smile
Jims 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 core
Galesburg CUSD #205
 
день народного единства
день народного единствадень народного единства
день народного единства
killaruns
 
Diseminare Curs Grundtvig, Malta 2012
Diseminare Curs Grundtvig, Malta 2012Diseminare Curs Grundtvig, Malta 2012
Diseminare Curs Grundtvig, Malta 2012
Tamara Petrof
 
Inforica Corporate Presentation
Inforica Corporate PresentationInforica Corporate Presentation
Inforica Corporate Presentation
Sudeep DSouza
 
O net คณิตศาสตร์ 2552
O net คณิตศาสตร์ 2552O net คณิตศาสตร์ 2552
O net คณิตศาสตร์ 2552
Justice MengKing
 
Refractometria joan l_ramos
Refractometria joan l_ramosRefractometria joan l_ramos
Refractometria joan l_ramos
aula20_2012
 
портфолио Шликова В.В.
портфолио Шликова В.В.портфолио Шликова В.В.
портфолио Шликова В.В.
TheShkola21
 
Mariana clavijo
Mariana clavijoMariana clavijo
Mariana clavijo
Mónica Molina
 
Project Development Brochure Hi Res
Project Development Brochure   Hi ResProject Development Brochure   Hi Res
Project Development Brochure Hi Res
nevwebb
 
13inmate project mkultra
13inmate project mkultra13inmate project mkultra
13inmate project mkultra
Lorenzo Dodi
 
Polymerase Chain Reaction
Polymerase Chain ReactionPolymerase Chain Reaction
Polymerase Chain Reaction
a b
 
Year 1 pupils' presentations
Year 1 pupils' presentationsYear 1 pupils' presentations
Year 1 pupils' presentations
lorcamollet
 
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
IDBS
 
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
nichoe10
 
Biblia hebraica stuttgartensia
Biblia hebraica stuttgartensiaBiblia hebraica stuttgartensia
Biblia hebraica stuttgartensia
gpelayomentor90
 
Ten words that makes you smile
Ten words that makes you smileTen words that makes you smile
Ten words that makes you smile
Jims 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 core
Galesburg CUSD #205
 
день народного единства
день народного единствадень народного единства
день народного единства
killaruns
 
Diseminare Curs Grundtvig, Malta 2012
Diseminare Curs Grundtvig, Malta 2012Diseminare Curs Grundtvig, Malta 2012
Diseminare Curs Grundtvig, Malta 2012
Tamara Petrof
 
Inforica Corporate Presentation
Inforica Corporate PresentationInforica Corporate Presentation
Inforica Corporate Presentation
Sudeep DSouza
 
O net คณิตศาสตร์ 2552
O net คณิตศาสตร์ 2552O net คณิตศาสตร์ 2552
O net คณิตศาสตร์ 2552
Justice MengKing
 
Refractometria joan l_ramos
Refractometria joan l_ramosRefractometria joan l_ramos
Refractometria joan l_ramos
aula20_2012
 
портфолио Шликова В.В.
портфолио Шликова В.В.портфолио Шликова В.В.
портфолио Шликова В.В.
TheShkola21
 
Project Development Brochure Hi Res
Project Development Brochure   Hi ResProject Development Brochure   Hi Res
Project Development Brochure Hi Res
nevwebb
 
Ad

Similar to Code Contracts (20)

Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code Contracts
Rainer Stropek
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
Antonio Radesca
 
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
Dmytro 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 -2013
David 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 Development
EffectiveUI
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
Effective
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
John 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 Xcode
Hiep Luong
 
AAA Automated Testing
AAA Automated TestingAAA Automated Testing
AAA Automated Testing
Francesco Carucci
 
High Productivity Web Development Workflow
High Productivity Web Development WorkflowHigh Productivity Web Development Workflow
High Productivity Web Development Workflow
Vũ 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 2014
Oliver N
 
Rock Your Code with Code Contracts
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code Contracts
David McCarter
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
guestc8093a6
 
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 Deploy
Adam Book
 
Coding Naked 2023
Coding Naked 2023Coding Naked 2023
Coding Naked 2023
Caleb Jenkins
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
Nate Abele
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
Nate 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 Lef
Katherine Golovinova
 
Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code Contracts
Rainer 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 right
Dmytro 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 -2013
David 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 Development
EffectiveUI
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
Effective
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
John 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 Xcode
Hiep Luong
 
High Productivity Web Development Workflow
High Productivity Web Development WorkflowHigh Productivity Web Development Workflow
High Productivity Web Development Workflow
Vũ 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 2014
Oliver N
 
Rock Your Code with Code Contracts
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code Contracts
David McCarter
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
guestc8093a6
 
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 Deploy
Adam Book
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
Nate Abele
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
Nate 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 Lef
Katherine Golovinova
 
Ad

More from Alexei Skachykhin (6)

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

Recently uploaded (20)

Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 

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.”
  • 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