SlideShare une entreprise Scribd logo
1  sur  39
David McCarter
dotnetdave@live.com
About David McCarter
•Microsoft MVP
•David McCarter’s .NET Coding Standards
•http://codingstandards.notlong.com/
•dotNetTips.com
•700+ Tips, Tricks, Articles, Links!
•Open Source Projects:
•http://codeplex.com/dotNetTips
•San Diego .NET Developers Group
•www.sddotnetdg.org
•UCSD Classes
•http://dotnetdaveclasses.notlong.com
@realdotnetdave
davidmccarter

dotnetdave@live.com
Conference DVD’s
• Rock Your Technical Interview DVD
• Full length video of session
• Expert Videos
• Engineer Videos
• Interview Questions
• Slide deck
• More!
• Rock Your Code DVD
• Videos of sessions
• Sides, sample code
• 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;

}




Contract.EnsuresOnThrow<T>
Contract.OldValue
Contract.ForAll




Collections

Contract.Ensures


Out parameters
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


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

Behavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowBehavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowRachid Kherrazi
 
Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Rapita Systems Ltd
 
Code Coverage and Test Suite Effectiveness: Empirical Study with Real Bugs in...
Code Coverage and Test Suite Effectiveness: Empirical Study with Real Bugs in...Code Coverage and Test Suite Effectiveness: Empirical Study with Real Bugs in...
Code Coverage and Test Suite Effectiveness: Empirical Study with Real Bugs in...Pavneet Singh Kochhar
 
Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy CodeAndrea Polci
 
Code Obfuscation for Android & WP7
Code Obfuscation for Android & WP7Code Obfuscation for Android & WP7
Code Obfuscation for Android & WP7Jeff Bollinger
 
Spec flow – functional testing made easy
Spec flow – functional testing made easySpec flow – functional testing made easy
Spec flow – functional testing made easyPaul Stack
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven DevelopmentPablo Villar
 
Test-Driven Development (TDD)
Test-Driven Development (TDD)Test-Driven Development (TDD)
Test-Driven Development (TDD)Brian Rasmussen
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentConsulthinkspa
 
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 PracticeAmar Shah
 
FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09Pyxis Technologies
 
Acceptance Test Driven Development With Spec Flow And Friends
Acceptance Test Driven Development With Spec Flow And FriendsAcceptance Test Driven Development With Spec Flow And Friends
Acceptance Test Driven Development With Spec Flow And FriendsChristopher Bartling
 
Test Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionTest Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionPyxis Technologies
 
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++Hong Le Van
 
TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019Paulo Clavijo
 

Tendances (20)

PHPUnit - Unit testing
PHPUnit - Unit testingPHPUnit - Unit testing
PHPUnit - Unit testing
 
Behavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowBehavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlow
 
Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage"
 
Code Coverage and Test Suite Effectiveness: Empirical Study with Real Bugs in...
Code Coverage and Test Suite Effectiveness: Empirical Study with Real Bugs in...Code Coverage and Test Suite Effectiveness: Empirical Study with Real Bugs in...
Code Coverage and Test Suite Effectiveness: Empirical Study with Real Bugs in...
 
Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy Code
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
 
Code Obfuscation for Android & WP7
Code Obfuscation for Android & WP7Code Obfuscation for Android & WP7
Code Obfuscation for Android & WP7
 
Spec flow – functional testing made easy
Spec flow – functional testing made easySpec flow – functional testing made easy
Spec flow – functional testing made easy
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
 
Write readable tests
Write readable testsWrite readable tests
Write readable tests
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Code
 
Test-Driven Development (TDD)
Test-Driven Development (TDD)Test-Driven Development (TDD)
Test-Driven Development (TDD)
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
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
 
FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09
 
Acceptance Test Driven Development With Spec Flow And Friends
Acceptance Test Driven Development With Spec Flow And FriendsAcceptance Test Driven Development With Spec Flow And Friends
Acceptance Test Driven Development With Spec Flow And Friends
 
Introduction to TDD and Mocking
Introduction to TDD and MockingIntroduction to TDD and Mocking
Introduction to TDD and Mocking
 
Test Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionTest Driven Development - Overview and Adoption
Test Driven Development - Overview and Adoption
 
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++
 
TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019
 

Similaire à Build Better Types with Code Contracts

Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code ContractsRainer Stropek
 
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...GlobalLogic Ukraine
 
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 Engineering Software Lab
 
TDD for Microservices
TDD for MicroservicesTDD for Microservices
TDD for MicroservicesVMware Tanzu
 
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
 
Unit_5 and Unit 6.pptx
Unit_5 and Unit 6.pptxUnit_5 and Unit 6.pptx
Unit_5 and Unit 6.pptxtaxegap762
 
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB
 
Advanced Coded UI Testing
Advanced Coded UI TestingAdvanced Coded UI Testing
Advanced Coded UI TestingShai Raiten
 
Tdd vs bdd vs atdd — developers’ methodologies to navigate complex developmen...
Tdd vs bdd vs atdd — developers’ methodologies to navigate complex developmen...Tdd vs bdd vs atdd — developers’ methodologies to navigate complex developmen...
Tdd vs bdd vs atdd — developers’ methodologies to navigate complex developmen...Katy Slemon
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentEffective
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentJohn Blanco
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentEffectiveUI
 
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.pptxBharat Chawda
 
Learn software testing with tech partnerz 1
Learn software testing with tech partnerz 1Learn software testing with tech partnerz 1
Learn software testing with tech partnerz 1Techpartnerz
 
Rhapsody Software
Rhapsody SoftwareRhapsody Software
Rhapsody SoftwareBill Duncan
 

Similaire à Build Better Types with Code Contracts (20)

Workshop: .NET Code Contracts
Workshop: .NET Code ContractsWorkshop: .NET Code Contracts
Workshop: .NET Code Contracts
 
Ensuring code quality
Ensuring code qualityEnsuring code quality
Ensuring code quality
 
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...
 
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
 
TDD for Microservices
TDD for MicroservicesTDD for Microservices
TDD for Microservices
 
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
 
Unit_5 and Unit 6.pptx
Unit_5 and Unit 6.pptxUnit_5 and Unit 6.pptx
Unit_5 and Unit 6.pptx
 
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDB
 
Advanced Coded UI Testing
Advanced Coded UI TestingAdvanced Coded UI Testing
Advanced Coded UI Testing
 
Coding Naked 2023
Coding Naked 2023Coding Naked 2023
Coding Naked 2023
 
Tdd vs bdd vs atdd — developers’ methodologies to navigate complex developmen...
Tdd vs bdd vs atdd — developers’ methodologies to navigate complex developmen...Tdd vs bdd vs atdd — developers’ methodologies to navigate complex developmen...
Tdd vs bdd vs atdd — developers’ methodologies to navigate complex developmen...
 
Unit iv
Unit ivUnit iv
Unit iv
 
Code Contracts API In .NET
Code Contracts API In .NETCode Contracts API In .NET
Code Contracts API In .NET
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
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
 
Learn software testing with tech partnerz 1
Learn software testing with tech partnerz 1Learn software testing with tech partnerz 1
Learn software testing with tech partnerz 1
 
Rhapsody Software
Rhapsody SoftwareRhapsody Software
Rhapsody Software
 

Plus de David McCarter

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 - V3David McCarter
 
Back-2-Basics: Code Contracts
Back-2-Basics: Code ContractsBack-2-Basics: Code Contracts
Back-2-Basics: Code ContractsDavid McCarter
 
How To Survive The Technical Interview
How To Survive The Technical InterviewHow To Survive The Technical Interview
How To Survive The Technical InterviewDavid McCarter
 
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 ServicesDavid McCarter
 
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 ServicesDavid McCarter
 
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 & ExtensionsDavid McCarter
 
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 .NETDavid McCarter
 
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)David McCarter
 
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)David McCarter
 
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 WorldDavid McCarter
 
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 WorldDavid McCarter
 
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)David McCarter
 
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)David McCarter
 
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 2010David McCarter
 

Plus de David McCarter (14)

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
 
Back-2-Basics: Code Contracts
Back-2-Basics: Code ContractsBack-2-Basics: Code Contracts
Back-2-Basics: Code Contracts
 
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

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 AutomationSafe Software
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
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 textsMaria Levchenko
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 

Dernier (20)

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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 

Build Better Types with Code Contracts

  • 2. About David McCarter •Microsoft MVP •David McCarter’s .NET Coding Standards •http://codingstandards.notlong.com/ •dotNetTips.com •700+ Tips, Tricks, Articles, Links! •Open Source Projects: •http://codeplex.com/dotNetTips •San Diego .NET Developers Group •www.sddotnetdg.org •UCSD Classes •http://dotnetdaveclasses.notlong.com @realdotnetdave davidmccarter dotnetdave@live.com
  • 3. Conference DVD’s • Rock Your Technical Interview DVD • Full length video of session • Expert Videos • Engineer Videos • Interview Questions • Slide deck • More! • Rock Your Code DVD • Videos of sessions • Sides, sample code • More!
  • 4. Overview Introducing Code Contracts Pre-conditions & Post-conditions Contract Your Types With Contracts Summary
  • 6.
  • 7.
  • 8.
  • 9.    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
  • 10. 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; }
  • 11. 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; }
  • 13.    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.
  • 14.  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
  • 15.  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
  • 16. Precondition  What does it expect? Postcondition  What does it promise?  What does it maintain? Class invariant
  • 17.      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/
  • 19.     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
  • 20. public static string FormatPhoneNumber(string str, bool bTakeOutDash) { Contract.Requires(string.IsNullOrWhiteSpace(str) == false); string str1 = str.Trim(); // code removed for brevity return str1; }
  • 21.
  • 22.
  • 23.
  • 24.
  • 25. 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; }
  • 26.    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.
  • 27. 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; }
  • 28.
  • 31.  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!
  • 32. public Int32 Value { get { return _value; } private set { if (this.Value != value) { if ((value <= this.Maximum) && (value >= this.Minimum)) { this._value = value; this.OnValueChanged(); } } } }
  • 33. 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(); } } } }
  • 34. 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 } }
  • 35.
  • 37.  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/
  • 39. 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