Code Contracts

31
DESIGN BY CONTRACT WITH CODE CONTRACTS

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.

Transcript of Code Contracts

Page 1: Code Contracts

DESIGN BY CONTRACTWITH CODE CONTRACTS

Page 2: Code Contracts

CONFESSION :(

Page 3: Code Contracts

Confession :(

“How many of you do write unit

tests?”

Page 4: Code Contracts

Confession :(

“How many of you do write documentation?”

Page 5: Code Contracts

Confession :(

“How many of you do write asserts?”

Page 6: Code Contracts

JUSTIFICATION :)

Page 7: Code Contracts

Justification :)THE GOOD PART

“At some extent all of these tools don`t work in a real

life.”- me

Page 8: Code Contracts

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

Page 9: Code Contracts

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

Page 10: Code Contracts

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

Page 11: Code Contracts

ConsequencesABANDONING

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

Page 12: Code Contracts

ConsequencesPROGRAMMING BY COINCIDENCE

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

programming deliberately.”- Dave Thomas

Page 13: Code Contracts

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

Page 14: Code Contracts

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

Page 15: Code Contracts

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

Page 16: Code Contracts

Design by ContractWHY?

“What are the benefits?”

Improved testability Runtime & Static Checking

Automatic generation of documentation

Discoverability of your API

Page 17: Code Contracts

Design by ContractIMPLEMENTATIONS FOR .NET

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

Page 18: Code Contracts
Page 19: Code Contracts

Microsoft Research

Page 20: Code Contracts

Code ContractsWHAT IS IT?

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

Proposed back in 2008.”

Page 21: Code Contracts

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

Page 22: Code Contracts

Code ContractsCOMPLETE API

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

blowing.”

Page 23: Code Contracts

Code ContractsCOMPONENTS

CCRewriteBinary Rewriter

CCCheckStatic Checker

CCDocGenXML Doc Extender

Page 24: Code Contracts

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

Page 25: Code Contracts

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

Page 26: Code Contracts

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

Page 27: Code Contracts

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

Page 28: Code Contracts

Code ContractsCONTRACT REFERENCE ASSEMBLIES

“Companion assemblies generated at compile time and contain only

contract portion of types.”

Page 29: Code Contracts

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

Page 30: Code Contracts

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

Page 31: Code Contracts

THANK YOU

Questions?