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

Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 

Recently uploaded (20)

Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 

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.