Code Contracts

Preview:

DESCRIPTION

Design By Contract with Code Contracts by Microsoft is a great technique allowing to push quality of the software we build to a next level.

Citation preview

DESIGN BY CONTRACTWITH 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

DocumentationNo documentation is

better than bad documentation

//declare variable foo as an integer and //set it to three.private int foo = 3;

CODE SNIPPET

Justification :)WATCH OUT

Unit testsAre 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);}

CODE SNIPPET

Justification :)WATCH OUT

AssertsMake little use for

calling code

public string Substring(int startIndex, int length)

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);}

CODE SNIPPET

ConsequencesABANDONING

“If so, why wouldn`t I abandon all this crap?”

ConsequencesPROGRAMMING BY COINCIDENCE

“We should avoid programming by coincidence - relying on luck and accidental successes - in favor of

programming deliberately.”- Dave Thomas

Design by ContractWHAT 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 MeyerEIFFEL PL, 1986

Design by ContractEIFFEL

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

CODE SNIPPET

class DATEinvariant valid_day: 1 <= day and day <= 31 valid_hour: 0 <= hour and hour <= 23end

CODE SNIPPET

Pre-conditions

Post-conditions

Invariants

Design by ContractRULES

Both parties must satisfy certain obligations, such as laws and regulations, applying to all contracts.

Metaphor : Client, Supplier agree on a Contract

1 The supplier must provide a certain product (obligation) and is entitled to expect that the client has paid its fee (benefit).

2 The client must pay the fee (obligation) and is entitled to get the product (benefit).

3

Design by ContractWHY?

“What are the benefits?”

Improved testability Runtime & Static Checking

Automatic generation of documentation

Discoverability of your API

Design by ContractIMPLEMENTATIONS FOR .NET

“Do we have similar concept in modern programming languages? Lets ask Microsoft.”

Microsoft Research

Code ContractsWHAT IS IT?

“Microsoft`s implementation of Design by Contract for .NET.

Proposed back in 2008.”

Code ContractsWHAT IS IT?

class WebService{ private IWarehouse store;

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

this.store = store; }

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

CODE SNIPPET

Pre-conditions

Post-conditions

Invariants

Code ContractsCOMPLETE API

“Mostly it is nice and easy, but occasionally it can be mind

blowing.”

Code ContractsCOMPONENTS

CCRewriteBinary Rewriter

CCCheckStatic Checker

CCDocGenXML Doc Extender

Code ContractsRUNTIME CHECKING

WebService.cs

WebService.dll

IL from body

IL from requires

IL from ensures

csc/vbc/… +ccrewrite

public WebService(IWarehouse store) {

}

this.store = store;

Contract.Requires(store != null);Contract.Ensures(this.store != null);

Code ContractsRUNTIME CHECKING (GENERAL CLIENTS)

WebService.cs

WebService.dll

IL from body

IL from requires

csc/vbc/… +ccrewrite

public WebService(IWarehouse store) {

}

this.store = store;

Contract.Requires(store != null);Contract.Ensures(this.store != null);

Code ContractsRUNTIME CHECKING (TRUSTED CLIENTS)

WebService.dll

IL from bodycsc/vbc/…

WebService.cs

public WebService(IWarehouse store) {

}

this.store = store;

Contract.Requires(store != null);Contract.Ensures(this.store != null);

Code ContractsDOCUMENTATION GENERATION

WebService.xml

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></member>

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><requires> store != null </requires><ensures> this.store != null </ensures></member>

ccdocgen

Code ContractsCONTRACT REFERENCE ASSEMBLIES

“Companion assemblies generated at compile time and contain only

contract portion of types.”

Code ContractsANNOYANCES

No way to execute post-conditions under lock statement

1 Static analysis is usually slow

2 Tools are failing from time to time

3

References

Code Contracts on MSDNhttp://msdn.microsoft.com/en-us/library/dd264808.aspx

Code Contractshttp://msdn.microsoft.com/en-us/magazine/ee236408.aspx

Code Contracts on Microsoft Researchhttp://research.microsoft.com/en-us/projects/contracts/

Code Contracts in C#http://www.infoq.com/articles/code-contracts-csharp

THANK YOU

Questions?

Recommended