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?

More Related Content

PDF
CI/CD non-breaking changes exercise - Cork Software Crafters - February 2020
PPTX
Consumer driven contracts in java world
PPTX
Contract based testing
PDF
Consumer-Driven Contract Testing
PDF
Angular and Redux
PDF
Approval Testing & Mutation Testing - Cork Software Crafters - June 2019
PPSX
The new way to extend VSTS Build and Release
PPTX
Dependency injection
CI/CD non-breaking changes exercise - Cork Software Crafters - February 2020
Consumer driven contracts in java world
Contract based testing
Consumer-Driven Contract Testing
Angular and Redux
Approval Testing & Mutation Testing - Cork Software Crafters - June 2019
The new way to extend VSTS Build and Release
Dependency injection

What's hot (12)

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

Viewers also liked (20)

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

Similar to Code Contracts (20)

PPTX
Enhance Your Code Quality with Code Contracts
PPTX
Design by Contract | Code Contracts in C# .NET
PPTX
Code Contracts API In .Net
PPTX
Code contracts by Dmytro Mindra
PPTX
Rock Your Code with Code Contracts
PPTX
.NET 4.0 Code Contracts (2010)
PPTX
Code Contracts API In .NET
ODP
Introduction to Contracts and Functional Contracts
PPTX
Code contracts
PPTX
Establishing a SOLID Foundation
PPTX
Rock Your Code With Code Contracts -2013
PPTX
Workshop: .NET Code Contracts
PDF
Contract First Development with Microsoft Code Contracts and Microsoft Pex at...
KEY
Solid principles
PDF
Clean code
PPTX
Back-2-Basics: Code Contracts
PPTX
Writing clean code in C# and .NET
PPTX
C:\Fakepath\Combating Software Entropy 2
PPTX
C:\Fakepath\Combating Software Entropy 2
PPTX
Combating software entropy 2-roc1-
Enhance Your Code Quality with Code Contracts
Design by Contract | Code Contracts in C# .NET
Code Contracts API In .Net
Code contracts by Dmytro Mindra
Rock Your Code with Code Contracts
.NET 4.0 Code Contracts (2010)
Code Contracts API In .NET
Introduction to Contracts and Functional Contracts
Code contracts
Establishing a SOLID Foundation
Rock Your Code With Code Contracts -2013
Workshop: .NET Code Contracts
Contract First Development with Microsoft Code Contracts and Microsoft Pex at...
Solid principles
Clean code
Back-2-Basics: Code Contracts
Writing clean code in C# and .NET
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
Combating software entropy 2-roc1-

More from Alexei Skachykhin (6)

PPTX
CSS Architecture: Writing Maintainable CSS
PPTX
Representational State Transfer
PPTX
Web Real-time Communications
PPTX
JavaScript as Development Platform
PDF
HTML5 Comprehensive Guide
PPTX
CSS Architecture: Writing Maintainable CSS
Representational State Transfer
Web Real-time Communications
JavaScript as Development Platform
HTML5 Comprehensive Guide

Recently uploaded (20)

PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
A Presentation on Artificial Intelligence
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Encapsulation theory and applications.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
cuic standard and advanced reporting.pdf
PPTX
Cloud computing and distributed systems.
PDF
Machine learning based COVID-19 study performance prediction
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
NewMind AI Monthly Chronicles - July 2025
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
“AI and Expert System Decision Support & Business Intelligence Systems”
A Presentation on Artificial Intelligence
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Encapsulation theory and applications.pdf
Spectral efficient network and resource selection model in 5G networks
Encapsulation_ Review paper, used for researhc scholars
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
cuic standard and advanced reporting.pdf
Cloud computing and distributed systems.
Machine learning based COVID-19 study performance prediction
Reach Out and Touch Someone: Haptics and Empathic Computing
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Understanding_Digital_Forensics_Presentation.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
NewMind AI Monthly Chronicles - July 2025

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