SlideShare a Scribd company logo
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

More Related Content

What's hot

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
 

What's hot (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
 

Similar to Rock Your Code With Code Contracts -2013

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
 

Similar to Rock Your Code With Code Contracts -2013 (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
 

More from 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
 

More from 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
 

Recently uploaded

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform EngineeringJemma Hussein Allen
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Alison B. Lowndes
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...Sri Ambati
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxAbida Shariff
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesThousandEyes
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...Elena Simperl
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»QADay
 

Recently uploaded (20)

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Ransomware Mallox [EN].pdf
Ransomware         Mallox       [EN].pdfRansomware         Mallox       [EN].pdf
Ransomware Mallox [EN].pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
 

Rock Your Code With Code Contracts -2013

  • 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