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?

Code Contracts

  • 1.
  • 2.
  • 3.
    Confession :( “How manyof you do write unit tests?”
  • 4.
    Confession :( “How manyof you do write documentation?”
  • 5.
    Confession :( “How manyof you do write asserts?”
  • 6.
  • 7.
    Justification :) THE GOODPART “At some extent all of these tools don`t work in a real life.” - me
  • 8.
    Justification :) WATCH OUT Documentation Nodocumentation 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 CODESNIPPET 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 CODESNIPPET 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, whywouldn`t I abandon all this crap?”
  • 12.
    Consequences PROGRAMMING BY COINCIDENCE “Weshould avoid programming by coincidence - relying on luck and accidental successes - in favor of programming deliberately.” - Dave Thomas
  • 13.
    Design by Contract WHATIS 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 CODESNIPPET 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? “Whatare the benefits?” Discoverability of your API Improved testability Runtime & Static Checking Automatic generation of documentation
  • 17.
    Design by Contract IMPLEMENTATIONSFOR .NET “Do we have similar concept in modern programming languages? Lets ask Microsoft.”
  • 19.
  • 20.
    Code Contracts WHAT ISIT? “Microsoft`s implementation of Design by Contract for .NET. Proposed back in 2008.”
  • 21.
    Code Contracts WHAT ISIT? 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 “Mostlyit is nice and easy, but occasionally it can be mind blowing.”
  • 23.
  • 24.
    Code Contracts RUNTIME CHECKING WebService.cs publicWebService(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>Constructsa 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 REFERENCEASSEMBLIES “Companion assemblies generated at compile time and contain only contract portion of types.”
  • 29.
    Code Contracts ANNOYANCES 1 2 3 Static analysisis 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 Contractson 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
  • 31.