SlideShare a Scribd company logo
Code Contracts DmytroMindra RnD Tech Lead LohikaLabs Пятая встреча Microsoft .Net User Group Одесса, 2011
© Drake Emko & Jen Brodzik, 2001
© Drake Emko & Jen Brodzik, 2001
© Drake Emko & Jen Brodzik, 2001
Design by Contract Bertrand Meyer DbC author Published 11 books including  “Object-Oriented Software Construction” First edition: 1988 Second edition: 1997
Terms Client must pay the fee (obligation) and is entitled to get the product (benefit). Supplier must provide a certain product (obligation) and is entitled to expect that the client has paid its fee (benefit) Contract. Both parties must satisfy certain obligations, such as laws and regulations, applying to all contracts
Terms
Contract Contract is precise and verifiable interface specifications for software components, which extend the ordinary definition of abstract data types with preconditions, postconditions and invariants. [8]
Contract Pre-conditions [9] In computer programming, a precondition is a condition or predicate that must always be true just prior to the execution of some section of code or before an operation in a formal specification. Post-conditions [10] 	In computer programming, a postcondition is a condition or predicate that must always be true just after the execution of some section of code or after an operation in a formal specification. Invariants[11] In computer science, a predicate is called an invariant to a sequence of operations provided that: if the predicate is true before starting the sequence, then it is true at the end of the sequence.
Contract verification Pre-condition fails Error in client code Post-condition or Invariant fails  Error in supplier code
Other approaches IF-THEN-TROW if(condition1) 	throw Exception1 if (condition2) 	throw Exception2 Debug.Assert Drawbacks: No Inheritance Inconvenient postconditions
Converting legacycontracts Converting if-throw 	void MyMethod(Foofoo){   if (foo == null) throw new ArgumentNullException(...);   Contract.EndContractBlock();   ... normal method code ...}
Spec# class Example { int x;   void Inc(int y) ensures old(x) < x;   {     x += y;   } }
New Generation Spec# Source code rewrite C# only (superset of C# v2.0) Code Contracts IL Rewrite Any language from VB to C# Faster
Code Contracts How to start using Code Contracts ?
Visual Studio 2010 Declarative contracts are included in .NET 4.0 (System.Diagnostics.Contracts) Tools are needed to  generate runtime checking from the contracts(ccrewrite) do a static check that verifies contracts at compile-time (cccheck) add contracts to the XML documentation files (ccdoc) LOCATION: [Program Files]icrosoftontractsinbr />
System.Diagnostics.Contracts Contract Attributes ContractClassAttribute ContractClassForAttribute ContractInvariantMethodAttribute ContractPublicPropertyNameAttribute ContractReferenceAssemblyAttribute ContractRuntimeIgnoredAttribute ContractVerificationAttribute PureAttribute ( is not enforced by analysis tools ) ContractFailedEventArgs ContractFailureKind (enum)
Contract methods Pre-conditions: 	Requires Post-conditions: 	Ensures Invariants: 		Invariant See also: 	EnsuresOnThrow<TException> 			Requires<TException>
Preconditions in Action     public class Customer {        private int _ID;        public int ID        {            get            {                return _ID;            }             		  set            {                		    if (value <= 0) throw new ArgumentException();                 		     _ID = value;            }        }} public class Customer{    private int _ID;    public int ID    {        get        {            return _ID;        }        set         { Contract.Requires(value > 0);            		 		 _ID = value;        }    }}
Demo: Basic + IL Spy
Processing collections Integer range ForAll(Int32, Int32, Predicate<Int32>) Exists(Int32, Int32, Predicate<Int32>) Collection ForAll<T>(IEnumerable<T>, Predicate<T>) Exists<T>(IEnumerable<T>, Predicate<T>)
Demo: Collections
Result processing OldValue<T> Result<T> ValueAtReturn<T>
Demo: Results
Other Assert - Checks for a condition Assume - Instructs code analysis tools to assume that the specified condition is true, even if it cannot be statically proven to always be true. Only for static checks. In runtime is treated like Assert. [3] EndContractBlock  - for legacy contracts
Assert & Assume public void Invoke()  {  int x = CalculateSomeValues();  // Tell the checker to verify whether // x>0.  // (The checker might  //  be unable to do it.)  Contract.Assert( x>0 );  // Rest of the code  } public void Invoke() {  int x = CalculateSomeValues();  // Explicitly tell the checker that  //x>0  Contract.Assume( x>0 ); // Rest of the code  }
Inheritance Two rules[7]: When you override a method (or implement an interface method) you inherit its contracts. You can't add extra preconditions to inherited ones, but you can make invariants and postconditions stronger.  E.g was require x>10 Added require x>100 Now x = 20 fulfills 1st require but violates 2nd;
Demo: Inheritance& Pitfalls
ContractFailed Handling Contract.ContractFailed +=  ContractContractFailed; static void ContractContractFailed( 		object sender, ContractFailedEventArgs e) { 		e.SetHandled(); // exception handledConsole.WriteLine(e.Message);}
Demo: ContractFailedfandling
custom contracts &custom rewriters methods public static class RuntimeFailureMethods {  public static void Requires(bool cond, string userMsg, string condText) { }  public static void Ensures(bool cond, string userMsg, string condText) { }… } See user manual 7.7. (page 34) [12]
Code snippets crContract.Requires(...); ce 		Contract.Ensures(...); ci 		Contract.Invariant(...); More in user manual 6.3. (page 26) [12]
Why not validate everything? Performance!
Summary and prospects Code Contracts are evolving BCL is driven by Code Contracts Static checking Code Contracts  may lead to better design Auto generated documentation Another tool in your toolbelt
PEX Path-based program exploration
Pex Demo
Additional reading
References [1] Design by Contract - A Conversation with Bertrand Meyer, Part II by Bill Venners http://www.artima.com/intv/contracts.html [2] Defensive programming http://en.wikipedia.org/wiki/Defensive_programming [3] Dino Esposito, Code Contracts Preview: Preconditions http://dotnetslackers.com/articles/net/Code-Contracts-Preview-Preconditions.aspx [4] Dino Esposito, Code Contracts Preview: PostConditions http://dotnetslackers.com/articles/net/Code-Contracts-Preview-PostConditions.aspx [5] Dino Esposito, Code Contracts Preview: Invariants http://dotnetslackers.com/articles/net/Code-Contracts-Preview-Invariants.aspx [6] Dino Esposito, Code Contracts Preview: Assert & Assume http://dotnetslackers.com/articles/net/Code-Contracts-Preview-Assert-Assume.aspx [7] Jon Skeet, Code Contracts in C# http://www.infoq.com/articles/code-contracts-csharp
References [8] Design by Contract - Wikipedia http://en.wikipedia.org/wiki/Design_by_contract [9] Precondition - Wikipedia http://en.wikipedia.org/wiki/Precondition [10] Postcondition - Wikipedia http://en.wikipedia.org/wiki/Postcondition [11] Invariant - Wikipedia http://en.wikipedia.org/wiki/Invariant_(computer_science) [12] Code Contracts User Manual http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf [13] Code contracts and inheritance http://stefanoricciardi.com/2009/07/17/code-contracts-and-inheritance/ [14] Assertions in Managed Code http://msdn.microsoft.com/en-us/library/ttcc4x86.aspx
C# 4.0 in a nutshell Page 508
Object-Oriented Software Construction Object-Oriented Software Construction Bertrand Meyer 1988,1997
Questions ?
Thank YOU !

More Related Content

What's hot

Scope of variables
Scope of variablesScope of variables
Scope of variables
Michael Gordon
 
The Ring programming language version 1.8 book - Part 44 of 202
The Ring programming language version 1.8 book - Part 44 of 202The Ring programming language version 1.8 book - Part 44 of 202
The Ring programming language version 1.8 book - Part 44 of 202
Mahmoud Samir Fayed
 
Final requirement in programming niperos
Final requirement in programming   niperosFinal requirement in programming   niperos
Final requirement in programming niperos
markings17
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
Seok-joon Yun
 
C#, What Is Next?
C#, What Is Next?C#, What Is Next?
C#, What Is Next?
Pieter Joost van de Sande
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
Seok-joon Yun
 
What's New In Python 2.6
What's New In Python 2.6What's New In Python 2.6
What's New In Python 2.6
Richard Jones
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3
rohassanie
 
C# 7.0, 7.1, 7.2
C# 7.0, 7.1, 7.2C# 7.0, 7.1, 7.2
C# 7.0, 7.1, 7.2
Miguel Angel Teheran Garcia
 
XMOS XS1 and XC
XMOS XS1 and XCXMOS XS1 and XC
XMOS XS1 and XC
Ruben Vandamme
 
Pythia Reloaded: An Intelligent Unit Testing-Based Code Grader for Education
Pythia Reloaded: An Intelligent Unit Testing-Based Code Grader for EducationPythia Reloaded: An Intelligent Unit Testing-Based Code Grader for Education
Pythia Reloaded: An Intelligent Unit Testing-Based Code Grader for Education
ECAM Brussels Engineering School
 

What's hot (11)

Scope of variables
Scope of variablesScope of variables
Scope of variables
 
The Ring programming language version 1.8 book - Part 44 of 202
The Ring programming language version 1.8 book - Part 44 of 202The Ring programming language version 1.8 book - Part 44 of 202
The Ring programming language version 1.8 book - Part 44 of 202
 
Final requirement in programming niperos
Final requirement in programming   niperosFinal requirement in programming   niperos
Final requirement in programming niperos
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
 
C#, What Is Next?
C#, What Is Next?C#, What Is Next?
C#, What Is Next?
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
What's New In Python 2.6
What's New In Python 2.6What's New In Python 2.6
What's New In Python 2.6
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3
 
C# 7.0, 7.1, 7.2
C# 7.0, 7.1, 7.2C# 7.0, 7.1, 7.2
C# 7.0, 7.1, 7.2
 
XMOS XS1 and XC
XMOS XS1 and XCXMOS XS1 and XC
XMOS XS1 and XC
 
Pythia Reloaded: An Intelligent Unit Testing-Based Code Grader for Education
Pythia Reloaded: An Intelligent Unit Testing-Based Code Grader for EducationPythia Reloaded: An Intelligent Unit Testing-Based Code Grader for Education
Pythia Reloaded: An Intelligent Unit Testing-Based Code Grader for Education
 

Viewers also liked

Spark-driven audience counting by Boris Trofimov
Spark-driven audience counting by Boris TrofimovSpark-driven audience counting by Boris Trofimov
Spark-driven audience counting by Boris Trofimov
JavaDayUA
 
Distilled mongo db by Boris Trofimov
Distilled mongo db by Boris TrofimovDistilled mongo db by Boris Trofimov
Distilled mongo db by Boris Trofimov
Alex Tumanoff
 
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
GeeksLab Odessa
 
Microsoft Office 2013 новая модель разработки приложений
Microsoft Office 2013 новая модель разработки приложенийMicrosoft Office 2013 новая модель разработки приложений
Microsoft Office 2013 новая модель разработки приложений
Alex Tumanoff
 
LightSwitch - different way to create business applications
LightSwitch - different way to create business applicationsLightSwitch - different way to create business applications
LightSwitch - different way to create business applications
Alex Tumanoff
 
Enterprise or not to enterprise
Enterprise or not to enterpriseEnterprise or not to enterprise
Enterprise or not to enterpriseAlex Tumanoff
 
Kostenko ux november-2014_1
Kostenko ux november-2014_1Kostenko ux november-2014_1
Kostenko ux november-2014_1
Alex Tumanoff
 

Viewers also liked (7)

Spark-driven audience counting by Boris Trofimov
Spark-driven audience counting by Boris TrofimovSpark-driven audience counting by Boris Trofimov
Spark-driven audience counting by Boris Trofimov
 
Distilled mongo db by Boris Trofimov
Distilled mongo db by Boris TrofimovDistilled mongo db by Boris Trofimov
Distilled mongo db by Boris Trofimov
 
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
 
Microsoft Office 2013 новая модель разработки приложений
Microsoft Office 2013 новая модель разработки приложенийMicrosoft Office 2013 новая модель разработки приложений
Microsoft Office 2013 новая модель разработки приложений
 
LightSwitch - different way to create business applications
LightSwitch - different way to create business applicationsLightSwitch - different way to create business applications
LightSwitch - different way to create business applications
 
Enterprise or not to enterprise
Enterprise or not to enterpriseEnterprise or not to enterprise
Enterprise or not to enterprise
 
Kostenko ux november-2014_1
Kostenko ux november-2014_1Kostenko ux november-2014_1
Kostenko ux november-2014_1
 

Similar to Code contracts by Dmytro Mindra

Code Contracts API In .NET
Code Contracts API In .NETCode Contracts API In .NET
Code Contracts API In .NET
Clarence Bakirtzidis
 
Solidity programming Language for beginners
Solidity programming Language for beginnersSolidity programming Language for beginners
Solidity programming Language for beginners
keshabkumar15
 
Code Contracts
Code ContractsCode Contracts
Code Contracts
Alexei Skachykhin
 
Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code Contracts
Rainer Stropek
 
.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
 
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
 
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
 
Code Contracts API In .Net
Code Contracts API In .NetCode Contracts API In .Net
Code Contracts API In .Net
melbournepatterns
 
Contract Practice with Remix
Contract Practice with RemixContract Practice with Remix
Contract Practice with Remix
KC Tam
 
Ethereummeetuppresentation01 170105172132
Ethereummeetuppresentation01 170105172132Ethereummeetuppresentation01 170105172132
Ethereummeetuppresentation01 170105172132
Rihazudin Razik MBCS
 
Ethereum Smart Contract Tutorial
Ethereum Smart Contract TutorialEthereum Smart Contract Tutorial
Ethereum Smart Contract Tutorial
Arnold Pham
 
Introduction to Contracts and Functional Contracts
Introduction to Contracts and Functional ContractsIntroduction to Contracts and Functional Contracts
Introduction to Contracts and Functional Contracts
Daniel Prager
 
Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)
Peter R. Egli
 
embeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptxembeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptx
sangeetaSS
 
Embedded C - Lecture 1
Embedded C - Lecture 1Embedded C - Lecture 1
Embedded C - Lecture 1
Mohamed Abdallah
 
Security in the blockchain
Security in the blockchainSecurity in the blockchain
Security in the blockchain
Bellaj Badr
 
Abstract Factory pattern application on multi-contract on-chain deployments
Abstract Factory pattern application on multi-contract on-chain deploymentsAbstract Factory pattern application on multi-contract on-chain deployments
Abstract Factory pattern application on multi-contract on-chain deployments
Dejan Radic
 
Software quality with Code Contracts and PEX - CodeCamp16oct2010
Software quality with Code Contracts and PEX - CodeCamp16oct2010Software quality with Code Contracts and PEX - CodeCamp16oct2010
Software quality with Code Contracts and PEX - CodeCamp16oct2010
Codecamp Romania
 
Write smart contract with solidity on Ethereum
Write smart contract with solidity on EthereumWrite smart contract with solidity on Ethereum
Write smart contract with solidity on Ethereum
Murughan Palaniachari
 
A coding fool design patterns
A coding fool design patternsA coding fool design patterns
A coding fool design patterns
leo_priv00
 

Similar to Code contracts by Dmytro Mindra (20)

Code Contracts API In .NET
Code Contracts API In .NETCode Contracts API In .NET
Code Contracts API In .NET
 
Solidity programming Language for beginners
Solidity programming Language for beginnersSolidity programming Language for beginners
Solidity programming Language for beginners
 
Code Contracts
Code ContractsCode Contracts
Code Contracts
 
Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code Contracts
 
.NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010).NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010)
 
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
 
Rock Your Code with Code Contracts
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code Contracts
 
Code Contracts API In .Net
Code Contracts API In .NetCode Contracts API In .Net
Code Contracts API In .Net
 
Contract Practice with Remix
Contract Practice with RemixContract Practice with Remix
Contract Practice with Remix
 
Ethereummeetuppresentation01 170105172132
Ethereummeetuppresentation01 170105172132Ethereummeetuppresentation01 170105172132
Ethereummeetuppresentation01 170105172132
 
Ethereum Smart Contract Tutorial
Ethereum Smart Contract TutorialEthereum Smart Contract Tutorial
Ethereum Smart Contract Tutorial
 
Introduction to Contracts and Functional Contracts
Introduction to Contracts and Functional ContractsIntroduction to Contracts and Functional Contracts
Introduction to Contracts and Functional Contracts
 
Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)
 
embeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptxembeddedc-lecture1-160404055102.pptx
embeddedc-lecture1-160404055102.pptx
 
Embedded C - Lecture 1
Embedded C - Lecture 1Embedded C - Lecture 1
Embedded C - Lecture 1
 
Security in the blockchain
Security in the blockchainSecurity in the blockchain
Security in the blockchain
 
Abstract Factory pattern application on multi-contract on-chain deployments
Abstract Factory pattern application on multi-contract on-chain deploymentsAbstract Factory pattern application on multi-contract on-chain deployments
Abstract Factory pattern application on multi-contract on-chain deployments
 
Software quality with Code Contracts and PEX - CodeCamp16oct2010
Software quality with Code Contracts and PEX - CodeCamp16oct2010Software quality with Code Contracts and PEX - CodeCamp16oct2010
Software quality with Code Contracts and PEX - CodeCamp16oct2010
 
Write smart contract with solidity on Ethereum
Write smart contract with solidity on EthereumWrite smart contract with solidity on Ethereum
Write smart contract with solidity on Ethereum
 
A coding fool design patterns
A coding fool design patternsA coding fool design patterns
A coding fool design patterns
 

More from Alex Tumanoff

Sql server 2019 New Features by Yevhen Nedaskivskyi
Sql server 2019 New Features by Yevhen NedaskivskyiSql server 2019 New Features by Yevhen Nedaskivskyi
Sql server 2019 New Features by Yevhen Nedaskivskyi
Alex Tumanoff
 
Odessa .net-user-group-sql-server-2019-hidden-gems by Denis Reznik
Odessa .net-user-group-sql-server-2019-hidden-gems by Denis ReznikOdessa .net-user-group-sql-server-2019-hidden-gems by Denis Reznik
Odessa .net-user-group-sql-server-2019-hidden-gems by Denis Reznik
Alex Tumanoff
 
Azure data bricks by Eugene Polonichko
Azure data bricks by Eugene PolonichkoAzure data bricks by Eugene Polonichko
Azure data bricks by Eugene Polonichko
Alex Tumanoff
 
Sdlc by Anatoliy Anthony Cox
Sdlc by  Anatoliy Anthony CoxSdlc by  Anatoliy Anthony Cox
Sdlc by Anatoliy Anthony Cox
Alex Tumanoff
 
Java 8 in action.jinq.v.1.3
Java 8 in action.jinq.v.1.3Java 8 in action.jinq.v.1.3
Java 8 in action.jinq.v.1.3
Alex Tumanoff
 
"Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас...
"Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас..."Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас...
"Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас...
Alex Tumanoff
 
Spring.new hope.1.3
Spring.new hope.1.3Spring.new hope.1.3
Spring.new hope.1.3
Alex Tumanoff
 
Sql saturday azure storage by Anton Vidishchev
Sql saturday azure storage by Anton VidishchevSql saturday azure storage by Anton Vidishchev
Sql saturday azure storage by Anton Vidishchev
Alex Tumanoff
 
Navigation map factory by Alexey Klimenko
Navigation map factory by Alexey KlimenkoNavigation map factory by Alexey Klimenko
Navigation map factory by Alexey KlimenkoAlex Tumanoff
 
Serialization and performance by Sergey Morenets
Serialization and performance by Sergey MorenetsSerialization and performance by Sergey Morenets
Serialization and performance by Sergey Morenets
Alex Tumanoff
 
Игры для мобильных платформ by Алексей Рыбаков
Игры для мобильных платформ by Алексей РыбаковИгры для мобильных платформ by Алексей Рыбаков
Игры для мобильных платформ by Алексей Рыбаков
Alex Tumanoff
 
Android sync adapter
Android sync adapterAndroid sync adapter
Android sync adapter
Alex Tumanoff
 
Async clinic by by Sergey Teplyakov
Async clinic by by Sergey TeplyakovAsync clinic by by Sergey Teplyakov
Async clinic by by Sergey TeplyakovAlex Tumanoff
 
Deep Dive C# by Sergey Teplyakov
Deep Dive  C# by Sergey TeplyakovDeep Dive  C# by Sergey Teplyakov
Deep Dive C# by Sergey TeplyakovAlex Tumanoff
 
Bdd by Dmitri Aizenberg
Bdd by Dmitri AizenbergBdd by Dmitri Aizenberg
Bdd by Dmitri AizenbergAlex Tumanoff
 
Неформальные размышления о сертификации в IT
Неформальные размышления о сертификации в ITНеформальные размышления о сертификации в IT
Неформальные размышления о сертификации в IT
Alex Tumanoff
 
Разработка расширений Firefox
Разработка расширений FirefoxРазработка расширений Firefox
Разработка расширений FirefoxAlex Tumanoff
 
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So..."AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
Alex Tumanoff
 
Patterns of parallel programming
Patterns of parallel programmingPatterns of parallel programming
Patterns of parallel programming
Alex Tumanoff
 
Lambda выражения и Java 8
Lambda выражения и Java 8Lambda выражения и Java 8
Lambda выражения и Java 8
Alex Tumanoff
 

More from Alex Tumanoff (20)

Sql server 2019 New Features by Yevhen Nedaskivskyi
Sql server 2019 New Features by Yevhen NedaskivskyiSql server 2019 New Features by Yevhen Nedaskivskyi
Sql server 2019 New Features by Yevhen Nedaskivskyi
 
Odessa .net-user-group-sql-server-2019-hidden-gems by Denis Reznik
Odessa .net-user-group-sql-server-2019-hidden-gems by Denis ReznikOdessa .net-user-group-sql-server-2019-hidden-gems by Denis Reznik
Odessa .net-user-group-sql-server-2019-hidden-gems by Denis Reznik
 
Azure data bricks by Eugene Polonichko
Azure data bricks by Eugene PolonichkoAzure data bricks by Eugene Polonichko
Azure data bricks by Eugene Polonichko
 
Sdlc by Anatoliy Anthony Cox
Sdlc by  Anatoliy Anthony CoxSdlc by  Anatoliy Anthony Cox
Sdlc by Anatoliy Anthony Cox
 
Java 8 in action.jinq.v.1.3
Java 8 in action.jinq.v.1.3Java 8 in action.jinq.v.1.3
Java 8 in action.jinq.v.1.3
 
"Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас...
"Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас..."Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас...
"Drools: декларативная бизнес-логика в Java-приложениях" by Дмитрий Контрерас...
 
Spring.new hope.1.3
Spring.new hope.1.3Spring.new hope.1.3
Spring.new hope.1.3
 
Sql saturday azure storage by Anton Vidishchev
Sql saturday azure storage by Anton VidishchevSql saturday azure storage by Anton Vidishchev
Sql saturday azure storage by Anton Vidishchev
 
Navigation map factory by Alexey Klimenko
Navigation map factory by Alexey KlimenkoNavigation map factory by Alexey Klimenko
Navigation map factory by Alexey Klimenko
 
Serialization and performance by Sergey Morenets
Serialization and performance by Sergey MorenetsSerialization and performance by Sergey Morenets
Serialization and performance by Sergey Morenets
 
Игры для мобильных платформ by Алексей Рыбаков
Игры для мобильных платформ by Алексей РыбаковИгры для мобильных платформ by Алексей Рыбаков
Игры для мобильных платформ by Алексей Рыбаков
 
Android sync adapter
Android sync adapterAndroid sync adapter
Android sync adapter
 
Async clinic by by Sergey Teplyakov
Async clinic by by Sergey TeplyakovAsync clinic by by Sergey Teplyakov
Async clinic by by Sergey Teplyakov
 
Deep Dive C# by Sergey Teplyakov
Deep Dive  C# by Sergey TeplyakovDeep Dive  C# by Sergey Teplyakov
Deep Dive C# by Sergey Teplyakov
 
Bdd by Dmitri Aizenberg
Bdd by Dmitri AizenbergBdd by Dmitri Aizenberg
Bdd by Dmitri Aizenberg
 
Неформальные размышления о сертификации в IT
Неформальные размышления о сертификации в ITНеформальные размышления о сертификации в IT
Неформальные размышления о сертификации в IT
 
Разработка расширений Firefox
Разработка расширений FirefoxРазработка расширений Firefox
Разработка расширений Firefox
 
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So..."AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
"AnnotatedSQL - провайдер с плюшками за 5 минут" - Геннадий Дубина, Senior So...
 
Patterns of parallel programming
Patterns of parallel programmingPatterns of parallel programming
Patterns of parallel programming
 
Lambda выражения и Java 8
Lambda выражения и Java 8Lambda выражения и Java 8
Lambda выражения и Java 8
 

Code contracts by Dmytro Mindra

  • 1. Code Contracts DmytroMindra RnD Tech Lead LohikaLabs Пятая встреча Microsoft .Net User Group Одесса, 2011
  • 2. © Drake Emko & Jen Brodzik, 2001
  • 3. © Drake Emko & Jen Brodzik, 2001
  • 4. © Drake Emko & Jen Brodzik, 2001
  • 5. Design by Contract Bertrand Meyer DbC author Published 11 books including “Object-Oriented Software Construction” First edition: 1988 Second edition: 1997
  • 6. Terms Client must pay the fee (obligation) and is entitled to get the product (benefit). Supplier must provide a certain product (obligation) and is entitled to expect that the client has paid its fee (benefit) Contract. Both parties must satisfy certain obligations, such as laws and regulations, applying to all contracts
  • 8. Contract Contract is precise and verifiable interface specifications for software components, which extend the ordinary definition of abstract data types with preconditions, postconditions and invariants. [8]
  • 9. Contract Pre-conditions [9] In computer programming, a precondition is a condition or predicate that must always be true just prior to the execution of some section of code or before an operation in a formal specification. Post-conditions [10] In computer programming, a postcondition is a condition or predicate that must always be true just after the execution of some section of code or after an operation in a formal specification. Invariants[11] In computer science, a predicate is called an invariant to a sequence of operations provided that: if the predicate is true before starting the sequence, then it is true at the end of the sequence.
  • 10. Contract verification Pre-condition fails Error in client code Post-condition or Invariant fails Error in supplier code
  • 11. Other approaches IF-THEN-TROW if(condition1) throw Exception1 if (condition2) throw Exception2 Debug.Assert Drawbacks: No Inheritance Inconvenient postconditions
  • 12. Converting legacycontracts Converting if-throw void MyMethod(Foofoo){   if (foo == null) throw new ArgumentNullException(...);   Contract.EndContractBlock();   ... normal method code ...}
  • 13. Spec# class Example { int x; void Inc(int y) ensures old(x) < x; { x += y; } }
  • 14. New Generation Spec# Source code rewrite C# only (superset of C# v2.0) Code Contracts IL Rewrite Any language from VB to C# Faster
  • 15. Code Contracts How to start using Code Contracts ?
  • 16. Visual Studio 2010 Declarative contracts are included in .NET 4.0 (System.Diagnostics.Contracts) Tools are needed to generate runtime checking from the contracts(ccrewrite) do a static check that verifies contracts at compile-time (cccheck) add contracts to the XML documentation files (ccdoc) LOCATION: [Program Files]icrosoftontractsinbr />
  • 17. System.Diagnostics.Contracts Contract Attributes ContractClassAttribute ContractClassForAttribute ContractInvariantMethodAttribute ContractPublicPropertyNameAttribute ContractReferenceAssemblyAttribute ContractRuntimeIgnoredAttribute ContractVerificationAttribute PureAttribute ( is not enforced by analysis tools ) ContractFailedEventArgs ContractFailureKind (enum)
  • 18. Contract methods Pre-conditions: Requires Post-conditions: Ensures Invariants: Invariant See also: EnsuresOnThrow<TException> Requires<TException>
  • 19. Preconditions in Action     public class Customer {        private int _ID;        public int ID        {            get            {                return _ID;            }             set            {                 if (value <= 0) throw new ArgumentException();                 _ID = value;            }        }} public class Customer{    private int _ID;    public int ID    {        get        {            return _ID;        }        set         { Contract.Requires(value > 0);             _ID = value;        }    }}
  • 20. Demo: Basic + IL Spy
  • 21. Processing collections Integer range ForAll(Int32, Int32, Predicate<Int32>) Exists(Int32, Int32, Predicate<Int32>) Collection ForAll<T>(IEnumerable<T>, Predicate<T>) Exists<T>(IEnumerable<T>, Predicate<T>)
  • 23. Result processing OldValue<T> Result<T> ValueAtReturn<T>
  • 25. Other Assert - Checks for a condition Assume - Instructs code analysis tools to assume that the specified condition is true, even if it cannot be statically proven to always be true. Only for static checks. In runtime is treated like Assert. [3] EndContractBlock - for legacy contracts
  • 26. Assert & Assume public void Invoke() { int x = CalculateSomeValues(); // Tell the checker to verify whether // x>0. // (The checker might // be unable to do it.) Contract.Assert( x>0 ); // Rest of the code } public void Invoke() { int x = CalculateSomeValues(); // Explicitly tell the checker that //x>0 Contract.Assume( x>0 ); // Rest of the code }
  • 27. Inheritance Two rules[7]: When you override a method (or implement an interface method) you inherit its contracts. You can't add extra preconditions to inherited ones, but you can make invariants and postconditions stronger. E.g was require x>10 Added require x>100 Now x = 20 fulfills 1st require but violates 2nd;
  • 29. ContractFailed Handling Contract.ContractFailed +=  ContractContractFailed; static void ContractContractFailed( object sender, ContractFailedEventArgs e) {  e.SetHandled(); // exception handledConsole.WriteLine(e.Message);}
  • 31. custom contracts &custom rewriters methods public static class RuntimeFailureMethods {  public static void Requires(bool cond, string userMsg, string condText) { }  public static void Ensures(bool cond, string userMsg, string condText) { }… } See user manual 7.7. (page 34) [12]
  • 32. Code snippets crContract.Requires(...); ce Contract.Ensures(...); ci Contract.Invariant(...); More in user manual 6.3. (page 26) [12]
  • 33. Why not validate everything? Performance!
  • 34. Summary and prospects Code Contracts are evolving BCL is driven by Code Contracts Static checking Code Contracts may lead to better design Auto generated documentation Another tool in your toolbelt
  • 35. PEX Path-based program exploration
  • 38. References [1] Design by Contract - A Conversation with Bertrand Meyer, Part II by Bill Venners http://www.artima.com/intv/contracts.html [2] Defensive programming http://en.wikipedia.org/wiki/Defensive_programming [3] Dino Esposito, Code Contracts Preview: Preconditions http://dotnetslackers.com/articles/net/Code-Contracts-Preview-Preconditions.aspx [4] Dino Esposito, Code Contracts Preview: PostConditions http://dotnetslackers.com/articles/net/Code-Contracts-Preview-PostConditions.aspx [5] Dino Esposito, Code Contracts Preview: Invariants http://dotnetslackers.com/articles/net/Code-Contracts-Preview-Invariants.aspx [6] Dino Esposito, Code Contracts Preview: Assert & Assume http://dotnetslackers.com/articles/net/Code-Contracts-Preview-Assert-Assume.aspx [7] Jon Skeet, Code Contracts in C# http://www.infoq.com/articles/code-contracts-csharp
  • 39. References [8] Design by Contract - Wikipedia http://en.wikipedia.org/wiki/Design_by_contract [9] Precondition - Wikipedia http://en.wikipedia.org/wiki/Precondition [10] Postcondition - Wikipedia http://en.wikipedia.org/wiki/Postcondition [11] Invariant - Wikipedia http://en.wikipedia.org/wiki/Invariant_(computer_science) [12] Code Contracts User Manual http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf [13] Code contracts and inheritance http://stefanoricciardi.com/2009/07/17/code-contracts-and-inheritance/ [14] Assertions in Managed Code http://msdn.microsoft.com/en-us/library/ttcc4x86.aspx
  • 40. C# 4.0 in a nutshell Page 508
  • 41. Object-Oriented Software Construction Object-Oriented Software Construction Bertrand Meyer 1988,1997