SlideShare a Scribd company logo
1 of 19
Besseres C#
Workshop
BASTA! Spring 2014

Rainer Stropek
software architects gmbh

Code Contracts

Web http://www.timecockpit.com
Mail rainer@timecockpit.com
Twitter @rstropek

Workshop
Saves the day.
What are Code Contracts
 Conditions
Preconditions
Postconditions
Object invariants

 Runtime

Checking

Rewrites IL Code
Conditional

 Static

Code Analysis

 Documentation
E.g. with Sandcastle
Code Contracts in .NET and VS
 System.Diagnostics.Contracts
 Visual

Studio Gallery

namespace
Runtime Checking
no

Runtime Checking
on Debug Builds
only

Checking in
Released
Code

yes

yes

Runtime Checking
on all Builds

Rewrite
Release
Builds?

no

Manual „if-thenthrow“, Runtime
Checking on Debug
Builds only
Contract.Requires(x != null);

Preconditions
// Use the following syntax if you need to throw a specific
// exception. This is only available if you run code contracts
// rewriter on all builds.
Contract.Requires<ArgumentNullException>(x != null, "x");

//
//
//
if
{

„Legacy requires“ – necessary if you want runtime checking
even on release builds without running code contracts
rewriter
( x == null )
// Single throw statement, nothing else!
throw new …Exception(…);

}
// No „else“ clause
…
// Necessary after all “legacy requires”
Contract.EndContractBlock();

Contract.Requires

Note that members
mentioned in preconditions
must have proper visibility
Important so that caller could check
precondition prior calling
See also
ContractPublicPropertyName
Contract.Ensures(this.X > 0);

Postconditions
// Postcondition in case of an exception
Contract.EnsuresOnThrow<Exception>(this.X == 0);

// Postcondition on result
Contract.Ensures(Contract.Result<int>() > 0);

// Accessing old values in ensures
Contract.Ensures(Contract.OldValue(this.X) < this.X);

// Postcondition on out variables
Contract.Ensures(Contract.ValueAtReturn(out x) > 0);

Contract.Ensures

Note that all postconditions
for async methods are
checked when the method
returns the task
Exception: Ensures that contain
Contract.Result<…>().Result
[ContractInvariantMethod]
private void ObjectInvariant()
{
// Nothing else than calls to Contract.Invariant
Contract.Invariant(this.x >= 0);
Contract.Invariant(this.x > this.y);
...
}

// Use invariants on automatic properties instead of pre- and
// postconditions
public int X { get; private set; }
[ContractInvariantMethod]
private void ObjectInvariant()
{
// Will become Contract.Ensures in property getter and
// Contract.Requires in property setter
Contract.Invariant(this.X >= 0);
}

Invariants
ContractInvariantMethod

Conditions indicating
whether an object is in a
valid state
Checked at the end of
each public method
// Checked during runtime and static code analysis
Contract.Assert(this.x > 0);
// Checked during runtime but not proven through static code
// analysis
Contract.Assume(this.x > 0);

Assert and Assume
Contract.Requires(Contract.ForAll(
listOfValues, // IEnumerable
value => value > 0));

// Indexed-based syntax
Contract.Ensures(Contract.ForAll(
0,
Contract.Result<int[]>().Length,
index => Contract.Result<int[]>()[index] > 0))

Quantifications
Alternatives
Contract.Exists
Enumerable.All
Enumerable.Any
static class ContractHelper
{
// Helper methods for „legacy requires“
[ContractArgumentValidator]
public static void NotNull(object arg, string paramName)
{
if (arg == null)
{
throw new ArgumentNullException(paramName, …);
}
Contract.EndContractBlock();
}

}

ContractHelper.NotNull(x, "x");

Contract Helpers
Use
ContractArgumentValidator
for legacy requires
Use ContractAbbreviator for
set of contracts
Contract Inheritance
 Contracts

are inherited

 Preconditions

must be defined at the root of the
inheritance chain

Ancestors cannot have weaker or stronger preconditions

 Add

stronger postconditions or invariants in ancestor
types if needed
Additional Topics
 Contracts

for interfaces and abstracts

See ContractClass and ContractClassFor

 Use

Pure attribute to mark side-effect free methods

Such methods can appear in contracts

 Explicitly

control runtime checking and inheritance

ContractRuntimeIgnored
ContractOption
Tips, Tricks, and Best Practices
 Do

you want to have runtime checking on release builds?

If yes, decide whether you want to run code contract rewriter on release builds

 Example
Debug

Source: Code Contracts User Docs

Release
[TestClass]
public class InitializeTests
{
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext tc)
{
Contract.ContractFailed += (sender, e) =>
{
e.SetUnwind(); // cause code to abort after event
Assert.Fail(e.FailureKind.ToString() + ":" + e.Message);
};
}
}

Tips, Tricks, and Best
Practices

Make sure that contract
failures are not hidden
with try-catch during unit
tests
Don‘t write unit tests to
intentionally contract
failures
Exception: Legacy requires
Tips, Tricks, and Best Practices
 If

necessary, you can alert other developers to use code
contract tools for building

 Code

contract tools install handy code snippets

 Deliver

a Contract Reference Assembly

Make contracts available to referencing assemblies

 Add

contract information in XML doc file

Sandcastle understands them
For details see Code Contracts User Docs
BASTA! Spring 2014

Rainer Stropek
software architects gmbh

Q&A

Mail rainer@timecockpit.com
Web http://www.timecockpit.com
Twitter @rstropek

Thank your for coming!
Saves the day.
is the leading time tracking solution for knowledge workers.
Graphical time tracking calendar, automatic tracking of your work using
signal trackers, high level of extensibility and customizability, full support to
work offline, and SaaS deployment model make it the optimal choice
especially in the IT consulting business.
Try
for free and without any risk. You can get your trial
account at http://www.timecockpit.com. After the trial period you can use
for only 0,20€ per user and day without a minimal subscription time and
without a minimal number of users.
ist die führende Projektzeiterfassung für Knowledge Worker.
Grafischer Zeitbuchungskalender, automatische Tätigkeitsaufzeichnung
über Signal Tracker, umfassende Erweiterbarkeit und Anpassbarkeit, volle
Offlinefähigkeit und einfachste Verwendung durch SaaS machen es zur
Optimalen Lösung auch speziell im IT-Umfeld.
Probieren Sie
kostenlos und ohne Risiko einfach aus. Einen
Testzugang erhalten Sie unter http://www.timecockpit.com. Danach nutzen
Sie
um nur 0,20€ pro Benutzer und Tag ohne Mindestdauer
und ohne Mindestbenutzeranzahl.

More Related Content

What's hot

Automated Historical Performance Analysis with kmemtracer
Automated Historical Performance Analysis with kmemtracerAutomated Historical Performance Analysis with kmemtracer
Automated Historical Performance Analysis with kmemtracerKyungmin Lee
 
Zend Framework Introduction
Zend Framework IntroductionZend Framework Introduction
Zend Framework IntroductionRafael Monteiro
 
JPQL/ JPA Activity 1
JPQL/ JPA Activity 1JPQL/ JPA Activity 1
JPQL/ JPA Activity 1SFI
 
Android Native Development Kit
Android Native Development KitAndroid Native Development Kit
Android Native Development KitPeter R. Egli
 
Intro to Angular.js & Zend2 for Front-End Web Applications
Intro to Angular.js & Zend2  for Front-End Web ApplicationsIntro to Angular.js & Zend2  for Front-End Web Applications
Intro to Angular.js & Zend2 for Front-End Web ApplicationsTECKpert, Hubdin
 
Spring Native and Spring AOT
Spring Native and Spring AOTSpring Native and Spring AOT
Spring Native and Spring AOTVMware Tanzu
 
From Ant to Maven to Gradle a tale of CI tools for JVM
From Ant to Maven to Gradle a tale of CI tools for JVMFrom Ant to Maven to Gradle a tale of CI tools for JVM
From Ant to Maven to Gradle a tale of CI tools for JVMBucharest Java User Group
 
Formacion en movilidad: Conceptos de desarrollo en iOS (I)
Formacion en movilidad: Conceptos de desarrollo en iOS (I) Formacion en movilidad: Conceptos de desarrollo en iOS (I)
Formacion en movilidad: Conceptos de desarrollo en iOS (I) Mobivery
 

What's hot (11)

Automated Historical Performance Analysis with kmemtracer
Automated Historical Performance Analysis with kmemtracerAutomated Historical Performance Analysis with kmemtracer
Automated Historical Performance Analysis with kmemtracer
 
Zend Framework Introduction
Zend Framework IntroductionZend Framework Introduction
Zend Framework Introduction
 
JPQL/ JPA Activity 1
JPQL/ JPA Activity 1JPQL/ JPA Activity 1
JPQL/ JPA Activity 1
 
Android Native Development Kit
Android Native Development KitAndroid Native Development Kit
Android Native Development Kit
 
NDK Introduction
NDK IntroductionNDK Introduction
NDK Introduction
 
Android NDK
Android NDKAndroid NDK
Android NDK
 
Intro to Angular.js & Zend2 for Front-End Web Applications
Intro to Angular.js & Zend2  for Front-End Web ApplicationsIntro to Angular.js & Zend2  for Front-End Web Applications
Intro to Angular.js & Zend2 for Front-End Web Applications
 
Android ndk: Entering the native world
Android ndk: Entering the native worldAndroid ndk: Entering the native world
Android ndk: Entering the native world
 
Spring Native and Spring AOT
Spring Native and Spring AOTSpring Native and Spring AOT
Spring Native and Spring AOT
 
From Ant to Maven to Gradle a tale of CI tools for JVM
From Ant to Maven to Gradle a tale of CI tools for JVMFrom Ant to Maven to Gradle a tale of CI tools for JVM
From Ant to Maven to Gradle a tale of CI tools for JVM
 
Formacion en movilidad: Conceptos de desarrollo en iOS (I)
Formacion en movilidad: Conceptos de desarrollo en iOS (I) Formacion en movilidad: Conceptos de desarrollo en iOS (I)
Formacion en movilidad: Conceptos de desarrollo en iOS (I)
 

Similar to Workshop: .NET Code Contracts

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 -2013David McCarter
 
.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
Rock Your Code with Code ContractsRock Your Code with Code Contracts
Rock Your Code with Code ContractsDavid McCarter
 
Design by Contract | Code Contracts in C# .NET
Design by Contract | Code Contracts in C# .NETDesign by Contract | Code Contracts in C# .NET
Design by Contract | Code Contracts in C# .NETDariusz Wozniak
 
Consumer driven contracts in java world
Consumer driven contracts in java worldConsumer driven contracts in java world
Consumer driven contracts in java worldYura Nosenko
 
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 - CodeCamp16oct2010Codecamp Romania
 
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발 [Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발 Yunho Maeng
 
2018 Cisco DevNet Create : How to Treat a Network as a Container
2018 Cisco DevNet Create : How to Treat a Network as a Container2018 Cisco DevNet Create : How to Treat a Network as a Container
2018 Cisco DevNet Create : How to Treat a Network as a ContainerRosemary Wang
 
TDD for Microservices
TDD for MicroservicesTDD for Microservices
TDD for MicroservicesVMware Tanzu
 
(Don't) Go Tracing Server Calls
(Don't) Go Tracing Server Calls(Don't) Go Tracing Server Calls
(Don't) Go Tracing Server CallsBrandon Hunter
 
Contract testing | Евгений Кузьмин | CODEiD
Contract testing | Евгений Кузьмин | CODEiDContract testing | Евгений Кузьмин | CODEiD
Contract testing | Евгений Кузьмин | CODEiDCODEiD PHP Community
 
WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...
WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...
WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...Amir Zmora
 
AWS Atlanta meetup Build Tools - Code Commit, Code Build, Code Deploy
AWS Atlanta meetup Build Tools - Code Commit, Code Build, Code DeployAWS Atlanta meetup Build Tools - Code Commit, Code Build, Code Deploy
AWS Atlanta meetup Build Tools - Code Commit, Code Build, Code DeployAdam Book
 
Improving code quality using CI
Improving code quality using CIImproving code quality using CI
Improving code quality using CIMartin de Keijzer
 
Susan windsor soft test 16th november 2005
Susan windsor soft test   16th november 2005Susan windsor soft test   16th november 2005
Susan windsor soft test 16th november 2005David O'Dowd
 

Similar to Workshop: .NET Code Contracts (20)

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
 
.NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010).NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010)
 
Code Contracts
Code ContractsCode Contracts
Code Contracts
 
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
 
Design by Contract | Code Contracts in C# .NET
Design by Contract | Code Contracts in C# .NETDesign by Contract | Code Contracts in C# .NET
Design by Contract | Code Contracts in C# .NET
 
Consumer driven contracts in java world
Consumer driven contracts in java worldConsumer driven contracts in java world
Consumer driven contracts in java world
 
Code Contracts API In .NET
Code Contracts API In .NETCode Contracts API In .NET
Code Contracts API In .NET
 
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
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
How to design, code, deploy and execute a smart contract
How to design, code, deploy and execute a smart contractHow to design, code, deploy and execute a smart contract
How to design, code, deploy and execute a smart contract
 
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발 [Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
 
2018 Cisco DevNet Create : How to Treat a Network as a Container
2018 Cisco DevNet Create : How to Treat a Network as a Container2018 Cisco DevNet Create : How to Treat a Network as a Container
2018 Cisco DevNet Create : How to Treat a Network as a Container
 
TDD for Microservices
TDD for MicroservicesTDD for Microservices
TDD for Microservices
 
(Don't) Go Tracing Server Calls
(Don't) Go Tracing Server Calls(Don't) Go Tracing Server Calls
(Don't) Go Tracing Server Calls
 
Contract testing | Евгений Кузьмин | CODEiD
Contract testing | Евгений Кузьмин | CODEiDContract testing | Евгений Кузьмин | CODEiD
Contract testing | Евгений Кузьмин | CODEiD
 
WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...
WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...
WebRTC Live Q&A Session #5 - JavaScript Promises and WebRTC Interoperability ...
 
AWS Atlanta meetup Build Tools - Code Commit, Code Build, Code Deploy
AWS Atlanta meetup Build Tools - Code Commit, Code Build, Code DeployAWS Atlanta meetup Build Tools - Code Commit, Code Build, Code Deploy
AWS Atlanta meetup Build Tools - Code Commit, Code Build, Code Deploy
 
Improving code quality using CI
Improving code quality using CIImproving code quality using CI
Improving code quality using CI
 
Susan windsor soft test 16th november 2005
Susan windsor soft test   16th november 2005Susan windsor soft test   16th november 2005
Susan windsor soft test 16th november 2005
 

Recently uploaded

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 

Recently uploaded (20)

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 

Workshop: .NET Code Contracts

  • 2. BASTA! Spring 2014 Rainer Stropek software architects gmbh Code Contracts Web http://www.timecockpit.com Mail rainer@timecockpit.com Twitter @rstropek Workshop Saves the day.
  • 3. What are Code Contracts  Conditions Preconditions Postconditions Object invariants  Runtime Checking Rewrites IL Code Conditional  Static Code Analysis  Documentation E.g. with Sandcastle
  • 4. Code Contracts in .NET and VS  System.Diagnostics.Contracts  Visual Studio Gallery namespace
  • 5. Runtime Checking no Runtime Checking on Debug Builds only Checking in Released Code yes yes Runtime Checking on all Builds Rewrite Release Builds? no Manual „if-thenthrow“, Runtime Checking on Debug Builds only
  • 6. Contract.Requires(x != null); Preconditions // Use the following syntax if you need to throw a specific // exception. This is only available if you run code contracts // rewriter on all builds. Contract.Requires<ArgumentNullException>(x != null, "x"); // // // if { „Legacy requires“ – necessary if you want runtime checking even on release builds without running code contracts rewriter ( x == null ) // Single throw statement, nothing else! throw new …Exception(…); } // No „else“ clause … // Necessary after all “legacy requires” Contract.EndContractBlock(); Contract.Requires Note that members mentioned in preconditions must have proper visibility Important so that caller could check precondition prior calling See also ContractPublicPropertyName
  • 7. Contract.Ensures(this.X > 0); Postconditions // Postcondition in case of an exception Contract.EnsuresOnThrow<Exception>(this.X == 0); // Postcondition on result Contract.Ensures(Contract.Result<int>() > 0); // Accessing old values in ensures Contract.Ensures(Contract.OldValue(this.X) < this.X); // Postcondition on out variables Contract.Ensures(Contract.ValueAtReturn(out x) > 0); Contract.Ensures Note that all postconditions for async methods are checked when the method returns the task Exception: Ensures that contain Contract.Result<…>().Result
  • 8. [ContractInvariantMethod] private void ObjectInvariant() { // Nothing else than calls to Contract.Invariant Contract.Invariant(this.x >= 0); Contract.Invariant(this.x > this.y); ... } // Use invariants on automatic properties instead of pre- and // postconditions public int X { get; private set; } [ContractInvariantMethod] private void ObjectInvariant() { // Will become Contract.Ensures in property getter and // Contract.Requires in property setter Contract.Invariant(this.X >= 0); } Invariants ContractInvariantMethod Conditions indicating whether an object is in a valid state Checked at the end of each public method
  • 9. // Checked during runtime and static code analysis Contract.Assert(this.x > 0); // Checked during runtime but not proven through static code // analysis Contract.Assume(this.x > 0); Assert and Assume
  • 10. Contract.Requires(Contract.ForAll( listOfValues, // IEnumerable value => value > 0)); // Indexed-based syntax Contract.Ensures(Contract.ForAll( 0, Contract.Result<int[]>().Length, index => Contract.Result<int[]>()[index] > 0)) Quantifications Alternatives Contract.Exists Enumerable.All Enumerable.Any
  • 11. static class ContractHelper { // Helper methods for „legacy requires“ [ContractArgumentValidator] public static void NotNull(object arg, string paramName) { if (arg == null) { throw new ArgumentNullException(paramName, …); } Contract.EndContractBlock(); } } ContractHelper.NotNull(x, "x"); Contract Helpers Use ContractArgumentValidator for legacy requires Use ContractAbbreviator for set of contracts
  • 12. Contract Inheritance  Contracts are inherited  Preconditions must be defined at the root of the inheritance chain Ancestors cannot have weaker or stronger preconditions  Add stronger postconditions or invariants in ancestor types if needed
  • 13. Additional Topics  Contracts for interfaces and abstracts See ContractClass and ContractClassFor  Use Pure attribute to mark side-effect free methods Such methods can appear in contracts  Explicitly control runtime checking and inheritance ContractRuntimeIgnored ContractOption
  • 14. Tips, Tricks, and Best Practices  Do you want to have runtime checking on release builds? If yes, decide whether you want to run code contract rewriter on release builds  Example Debug Source: Code Contracts User Docs Release
  • 15. [TestClass] public class InitializeTests { [AssemblyInitialize] public static void AssemblyInitialize(TestContext tc) { Contract.ContractFailed += (sender, e) => { e.SetUnwind(); // cause code to abort after event Assert.Fail(e.FailureKind.ToString() + ":" + e.Message); }; } } Tips, Tricks, and Best Practices Make sure that contract failures are not hidden with try-catch during unit tests Don‘t write unit tests to intentionally contract failures Exception: Legacy requires
  • 16. Tips, Tricks, and Best Practices  If necessary, you can alert other developers to use code contract tools for building  Code contract tools install handy code snippets  Deliver a Contract Reference Assembly Make contracts available to referencing assemblies  Add contract information in XML doc file Sandcastle understands them For details see Code Contracts User Docs
  • 17. BASTA! Spring 2014 Rainer Stropek software architects gmbh Q&A Mail rainer@timecockpit.com Web http://www.timecockpit.com Twitter @rstropek Thank your for coming! Saves the day.
  • 18. is the leading time tracking solution for knowledge workers. Graphical time tracking calendar, automatic tracking of your work using signal trackers, high level of extensibility and customizability, full support to work offline, and SaaS deployment model make it the optimal choice especially in the IT consulting business. Try for free and without any risk. You can get your trial account at http://www.timecockpit.com. After the trial period you can use for only 0,20€ per user and day without a minimal subscription time and without a minimal number of users.
  • 19. ist die führende Projektzeiterfassung für Knowledge Worker. Grafischer Zeitbuchungskalender, automatische Tätigkeitsaufzeichnung über Signal Tracker, umfassende Erweiterbarkeit und Anpassbarkeit, volle Offlinefähigkeit und einfachste Verwendung durch SaaS machen es zur Optimalen Lösung auch speziell im IT-Umfeld. Probieren Sie kostenlos und ohne Risiko einfach aus. Einen Testzugang erhalten Sie unter http://www.timecockpit.com. Danach nutzen Sie um nur 0,20€ pro Benutzer und Tag ohne Mindestdauer und ohne Mindestbenutzeranzahl.