SlideShare une entreprise Scribd logo
1  sur  40
David McCarter
dotnetdave@live.com
Conference DVD’s
• Rock Your Code DVD
• Videos of sessions
• Sides, sample code
• More!
• Rock Your Technical Interview DVD
• Full length video of session
• Expert Videos
• Engineer Videos
• Interview Questions
• Slide deck
• More!
Overview
Introducing Code Contracts
Pre-conditions & Post-conditions
Contract Your Types With Contracts

Summary
Overview





Always check for valid parameter
arguments!
Perform argument validation for every public
or protected method
Throw meaningful exceptions to the
developer for invalid parameter arguments



Use the System.ArgumentException class
Or your own class derived from
System.ArgumentException
public string FormatPhoneNumber(string str, bool bTakeOutDash)
{
string str1 = str.Trim();
if (bTakeOutDash)
{
if (11 == str.Length && -1 != str.IndexOf('-'))
{
str1 = "";
for (int i = 0; i < str.Length; i++)
{
if ("-" != str.Substring(i, 1))
{
str1 = string.Concat(str1, str.Substring(i, 1));
}
}
}
}
return str1;
}
public string FormatPhoneNumber(string str, bool bTakeOutDash)
{
if (string.IsNullOrWhiteSpace(str))
{
throw new ArgumentNullException("str", "Phone number must be supplied.");
}
string str1 = str.Trim();
if (bTakeOutDash)
{
// Code Removed for brevity
}
return str1;
}
Introducing
Code Contracts

Build Better Types





Is an approach for designing software.
It prescribes that software designers should
define formal, precise and verifiable interface
specifications for software components, which
extend the ordinary definition of abstract data
types with preconditions, post-conditions and
invariants.
These specifications are referred to as
"contracts", in accordance with a conceptual
metaphor with the conditions and obligations of
business contracts.


A discipline of
analysis, design, implementation, management



Applications throughout the software lifecycle:


Getting the software right:









analysis, design , implementation

Debugging & testing
Automatic documentation
Getting inheritance right
Getting exception handling right!
Maintenance
Management


Every software element is intended to
satisfy a certain goal, or contract




For the benefit of other software elements (and
ultimately of human users)

The contract of any software element should
be



Explicit
Part of the software element itself
Precondition



What does it expect?
Postcondition



What does it promise?



What does it maintain?

Class
invariant







New API + tools from Microsoft for Designby-Contract
System.Diagnostics.Contracts
MSIL rewriting
Inspired by Spec#
Included in .NET 4.0/ 4.5


Latest version released 9/13



http://research.microsoft.com/en-us/projects/contracts/
Pre-conditions
Post-conditions

Oh My!





Usually for method parameter checking
Caller’s responsibility to make sure the
precondition is true on entry into method
Does not need to be compiled in production
code
Can also include throwing of Exceptions


These must be compiled into assembly
public static string FormatPhoneNumber(string str, bool bTakeOutDash)
{
Contract.Requires(string.IsNullOrWhiteSpace(str) == false);
string str1 = str.Trim();
// code removed for brevity
return str1;
}
public static string FormatPhoneNumber(string str, bool bTakeOutDash)
{
Contract.Requires<ArgumentNullException>
(string.IsNullOrWhiteSpace(str) == false);
string str1 = str.Trim();

// code removed for brevity
return str1;
}




Postconditions are contracts for the state of
a method when it terminates
The postcondition is checked just before
exiting a method
The run-time behavior of failed
postconditions is determined by the runtime
analyzer.
public static string FormatPhoneNumber(string str, bool bTakeOutDash)
{
Contract.Requires(string.IsNullOrWhiteSpace(str) == false);
Contract.Ensures(string.IsNullOrEmpty(Contract.Result<string>())
==false);
string str1 = str.Trim();
// code removed for brevity
return str1;

}




EnsuresOnThrow<T>
OldValue
ForAll




Ensures




Out parameters

EndContractBlock




Collections

Legacy parameter checking

Abstract Methods, Overloaded Methods and more!
Contract Your
Types
With Contracts
Creates MUCH Better Types!


ContractInvariantMethod







Mark methods that contain object invariant
specifications
The methods marked with this attribute must
be nullary methods with void return types and
contain nothing other than calls to Contract
You may not call these methods from within
your code.

Force coders to do proper value checking!
public Int32 Value
{
get { return _value; }
private set
{
if (this.Value != value)
{
if ((value <= this.Maximum) && (value >= this.Minimum))
{
this._value = value;
this.OnValueChanged();
}
}
}
}
public Int32 Value
{
get { return _value; }
private set
{
if (this.Value != value)
{
Contract.Requires<ArgumentOutOfRangeException>(value >= 0);
if ((value <= this.Maximum) && (value >= this.Minimum))
{
this._value = value;
this.OnValueChanged();
}
}
}
}
private Int32 _value;
[ContractInvariantMethod]
private void Invariants()
{
Contract.Invariant(_value >= 0,
"Value cannot be less than zero.");
}
-------------------------------------set
{
// Contract.Requires<ArgumentOutOfRangeException>(value >= 0);
if (this.Value != value)
{
// Code Removed for Brevity
}
}
Summary




Asserts
Inheritance
Attributes












ContractClass, ContractClassFor
Pure
RuntimeContracts
ContractPublicPropertyName
ContractVerification
ContractRuntimeIgnored
ContractOption

Contracting Ordering
Lots more!


Pex and Moles






Isolation and White box Unit Testing for .NET
Pex auto generates test suites with high code
coverage
Moles supports unit testing by way of detours
and stubs (delegates)

http://research.microsoft.com/en-us/projects/pex/


Microsoft Research




http://research.microsoft.com/enus/projects/contracts/

Channel 9


http://channel9.msdn.com/Search/?Term=code
%20contracts
Questions?

All Pictures & Videos © David McCarter

•Presentation Downloads
•slideshare.com/dotnetdave
•Please Rate My Session:
•speakerrate.com/dotnetdave
•David McCarter’s
•.NET Coding Standards
•dotnettips.com
•Geek Swag
•geekstuff.notlong.com
@realdotnetdave
davidmccarter

dotnetdave@live.com

Contenu connexe

Tendances

Introduction to automated quality assurance
Introduction to automated quality assuranceIntroduction to automated quality assurance
Introduction to automated quality assurance
Philip Johnson
 
The "Evils" of Optimization
The "Evils" of OptimizationThe "Evils" of Optimization
The "Evils" of Optimization
BlackRabbitCoder
 

Tendances (20)

Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Introduction to automated quality assurance
Introduction to automated quality assuranceIntroduction to automated quality assurance
Introduction to automated quality assurance
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in Practice
 
Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An Introduction
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Code
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Code
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
 
Professional Code Reviews - Bogdan Gusiev
Professional Code Reviews - Bogdan GusievProfessional Code Reviews - Bogdan Gusiev
Professional Code Reviews - Bogdan Gusiev
 
Journey's diary developing a framework using tdd
Journey's diary   developing a framework using tddJourney's diary   developing a framework using tdd
Journey's diary developing a framework using tdd
 
Code smells and remedies
Code smells and remediesCode smells and remedies
Code smells and remedies
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed Shreef
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
The "Evils" of Optimization
The "Evils" of OptimizationThe "Evils" of Optimization
The "Evils" of Optimization
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
Cursus phpunit
Cursus phpunitCursus phpunit
Cursus phpunit
 
Ch 6 randomization
Ch 6 randomizationCh 6 randomization
Ch 6 randomization
 
Bad Code Smells
Bad Code SmellsBad Code Smells
Bad Code Smells
 

Similaire à Rock Your Code with Code Contracts

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
 
CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019
Olivera Milenkovic
 

Similaire à Rock Your Code with Code Contracts (20)

Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code Contracts
 
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
 
SWE-6 TESTING.pptx
SWE-6 TESTING.pptxSWE-6 TESTING.pptx
SWE-6 TESTING.pptx
 
Code Contracts API In .NET
Code Contracts API In .NETCode Contracts API In .NET
Code Contracts API In .NET
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
.NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010).NET 4.0 Code Contracts (2010)
.NET 4.0 Code Contracts (2010)
 
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
Parasoft .TEST, Write better C# Code Using  Data Flow Analysis Parasoft .TEST, Write better C# Code Using  Data Flow Analysis
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
 
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
 
Ensuring code quality
Ensuring code qualityEnsuring code quality
Ensuring code quality
 
SE2023 0401 Software Coding and Testing.pptx
SE2023 0401 Software Coding and Testing.pptxSE2023 0401 Software Coding and Testing.pptx
SE2023 0401 Software Coding and Testing.pptx
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Conformiq Tutorial
Conformiq TutorialConformiq Tutorial
Conformiq Tutorial
 
Code Contracts
Code ContractsCode Contracts
Code Contracts
 
Introduction to Contracts and Functional Contracts
Introduction to Contracts and Functional ContractsIntroduction to Contracts and Functional Contracts
Introduction to Contracts and Functional Contracts
 
Martin Gijsen - Effective Test Automation a la Carte
Martin Gijsen -  Effective Test Automation a la Carte Martin Gijsen -  Effective Test Automation a la Carte
Martin Gijsen - Effective Test Automation a la Carte
 
AAA Automated Testing
AAA Automated TestingAAA Automated Testing
AAA Automated Testing
 
CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019
 
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
 

Plus de David McCarter

Plus de David McCarter (13)

Röck Yoür Technical Interview - V3
Röck Yoür Technical Interview - V3Röck Yoür Technical Interview - V3
Röck Yoür Technical Interview - V3
 
How To Survive The Technical Interview
How To Survive The Technical InterviewHow To Survive The Technical Interview
How To Survive The Technical Interview
 
Real World API Design Using The Entity Framework Services
Real World API Design Using The Entity Framework ServicesReal World API Design Using The Entity Framework Services
Real World API Design Using The Entity Framework Services
 
Building nTier Applications with Entity Framework Services
Building nTier Applications with Entity Framework ServicesBuilding nTier Applications with Entity Framework Services
Building nTier Applications with Entity Framework Services
 
Code Easier With Visual Studio 2010 & Extensions
Code Easier With Visual Studio 2010 & ExtensionsCode Easier With Visual Studio 2010 & Extensions
Code Easier With Visual Studio 2010 & Extensions
 
Back-2-Basics: Exception & Event Instrumentation in .NET
Back-2-Basics: Exception & Event Instrumentation in .NETBack-2-Basics: Exception & Event Instrumentation in .NET
Back-2-Basics: Exception & Event Instrumentation in .NET
 
Building nTier Applications with Entity Framework Services (Part 2)
Building nTier Applications with Entity Framework Services (Part 2)Building nTier Applications with Entity Framework Services (Part 2)
Building nTier Applications with Entity Framework Services (Part 2)
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real World
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real World
 
Building nTier Applications with Entity Framework Services (Part 2)
Building nTier Applications with Entity Framework Services (Part 2)Building nTier Applications with Entity Framework Services (Part 2)
Building nTier Applications with Entity Framework Services (Part 2)
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Building N Tier Applications With Entity Framework Services 2010
Building N Tier Applications With Entity Framework Services 2010Building N Tier Applications With Entity Framework Services 2010
Building N Tier Applications With Entity Framework Services 2010
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Dernier (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Rock Your Code with Code Contracts