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

Rock Your Code With Code Contracts -2013

  • 1.
  • 2.
    About David McCarter •MicrosoftMVP •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 • RockYour 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
  • 5.
  • 9.
       Always check forvalid 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(stringstr, 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(stringstr, 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; }
  • 12.
  • 13.
       Is an approachfor 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 elementis 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 itexpect? 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/
  • 18.
  • 19.
        Usually for methodparameter 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 stringFormatPhoneNumber(string str, bool bTakeOutDash) { Contract.Requires(string.IsNullOrWhiteSpace(str) == false); string str1 = str.Trim(); // code removed for brevity return str1; }
  • 25.
    public static stringFormatPhoneNumber(string str, bool bTakeOutDash) { Contract.Requires<ArgumentNullException> (string.IsNullOrWhiteSpace(str) == false); string str1 = str.Trim(); // code removed for brevity return str1; }
  • 26.
       Postconditions are contractsfor 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 stringFormatPhoneNumber(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; }
  • 29.
  • 30.
  • 31.
     ContractInvariantMethod     Mark methods thatcontain 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] privatevoid 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 } }
  • 36.
  • 37.
     Pex and Moles     Isolationand 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/
  • 38.
  • 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