SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Putting a Hit on Bugs
with Code Contracts
Software needs Reliability
• Two Components
   Correctness
     • Does what it’s supposed to do and only that
   Robustness
     • Acts appropriately in cases where it cannot do what it is
       supposed to do
But What’s it Supposed to Do?
Describing Software
• How do developers express what software
  is supposed to do?
  A. Write it in English, allowing your users/clients to
     approve it beforehand?
  B. Write it in the comments?
  C. Describe it in a format system based on discrete
     mathematics
  D. Poorly?
  E. All of the above?
Correctness of a Routine
• State the conditions that must be true
  before the routine can work correctly
   Pre-conditions
• State the conditions that will be true after
  execution, if the routine has worked
  correctly
   Post-conditions
Let’s Consider an Example
• Create a class that implements a time of day
   Exposes hour, minute, second properties
   Implementation could be as three separate integers or as
    the number of seconds since midnight
• We’re going to look only at the process of
  assigning the hour
Contracts

 • Document assumptions
    Preconditions, postconditions, invariants
 • Are executable
    Can perform checks at run-time
 • Help with static verification
    Assist with early error detection
    Can be used by tools to generate test cases
 • Different than assertions
    Assertions are not viewed as a contract, they are
     a suggestion
    Difficult to use with test case generation tools
What Contracts Can I Write?

 • Requires
    What must be true at method entry
 • Ensures
    What must be true at method exit
    Includes exits on exceptions
 • Invariants
    What must be true at all method exits
 • Assertions
    What must be true at a particular point
 • Assumptions
    What should be true at a particular point
What Can I Put In A Contract?

 • Any boolean expression
    In your favorite programming language!
    Including method calls (but must
     be marked Pure)
 • Contract.Result
    refer to the return value of the method
 • Contract.OldValue
    refer to values at method entry
 • Quantifiers
    Contract.ForAll(0,A.Length, Function(i) A(i) > 0);
    Contract.Exists(0,A.Length, Function(i) A(i) > 0);
Public Overridable Function Add(value As Object) As Integer{
       Contract.Requires( value IsNot Nothing )

           Contract.Ensures( Count = Contract.OldValue(Of Integer)(Count) + 1 )
           Contract.Ensures( Contract.Result(Of Integer)() = _
              Contract.OldValue(Of Integer)(Count) )
                                                                                                                                                                                                  Executable Runtime
                                                                                                                                                                                                  Contract Checking
           if (_size == _items.Length) EnsureCapacity(_size+1);
           _items[_size] = value;                                                                                                                                                                 .method public hidebysig newslot virtual instance int32 Add(object 'value') cil managed
                                                                                                                                                                                                  {
                                                                                                                                                                                                    .locals init (int32 'Contract.Old(Count)',

           return _size++;                                                                                                                                                                                     int32 'Contract.Result<int>()')
                                                                                                                                                                                                    ldarg.0
                                                                                                                                                                                                    call      instance int32 TabDemo.BaseList::get_Count()

     }                                                                                                                                                                                              stloc.3
                                                                                                                                                                                                    ldarg.1
                                                                                                                                                                                                    ldnull

csc/vbc/…                                                                                                                                                                                           ceq
                                                                                                                                                                                                    ldc.i4.0
                                                                                            .method public hidebysig newslot virtual instance int32 Add(object 'value') cil managed
                                                                                                                                                                                                    ceq
                                                                                            {
                                                                                                                                                                                                    ldstr      quot;value != nullquot;
                                                                                              ldarg.1
                                                                                                                                                                                                    call      void __RewriterMethods::RewriterRequires$PST06000009(bool, string)
                                                                                              ldnull

                                   /d:CONTRACTS_FULL
Release                                                                                                                                                                                             ldarg.0
                                                                                              ceq
                                                                                                                                                                                                    ldfld      int32 TabDemo.BaseList::count
                                                                                              ldc.i4.0
                                                                                                                                                                                                    ldarg.0
                                                                                              ceq
                                                                                                                                                                                                    ldfld      object[] TabDemo.BaseList::items
                                                                                              call     void [Microsoft.Contracts]Microsoft.Contracts.Contract::Requires(bool)

Compile                                                                                                                                                                                             ldlen
                                                                                              ldarg.0
                                                                                                                                                                                                    conv.i4
                                                                                              call     instance int32 TabDemo.BaseList::get_Count()


                                                                            csc/vbc/…
                                                                                                                                                                                                    ceq
                                                                                              ldarg.0
                                                                                                                                                                                                    ldc.i4.0
                                                                                              call     instance int32 TabDemo.BaseList::get_Count()
                                                                                                                                                                                                    ceq
                                                                                              call     !!0 [Microsoft.Contracts]Microsoft.Contracts.Contract::Old<int32>(!!0)
                                                                                                                                                                                                    stloc.1
                                                                                              ldc.i4.1
                                                                                                                                                                                                    ldloc.1
                                                                                              add
                                                                                                                                                                                                    brtrue IL_004d
                                                                                              ceq
                                                                                                                                                                                                    nop
                                                                                              call     void [Microsoft.Contracts]Microsoft.Contracts.Contract::Ensures(bool)
                                                                                                                                                                                                    ldarg.0
                                                                                              call     !!0 [Microsoft.Contracts]Microsoft.Contracts.Contract::Result<int32>()
                                                                                                                                                                                      ccrewrite     ldarg.0
                                                                                              ldarg.0
                                                                                                                                                                                                    ldfld      int32 TabDemo.BaseList::count
                                                                                              call     instance int32 TabDemo.BaseList::get_Count()
                                                                                                                                                                                                    ldc.i4.1
  .method public hidebysig newslot virtual instance int32 Add(object 'value') cil managed     call     !!0 [Microsoft.Contracts]Microsoft.Contracts.Contract::Old<int32>(!!0)
                                                                                                                                                                                                    add
  {                                                                                           ceq
                                                                                                                                                                                                    call      instance void TabDemo.BaseList::EnsureCapacity(int32)
    ldarg.0                                                                                   call     void [Microsoft.Contracts]Microsoft.Contracts.Contract::Ensures(bool)
                                                                                                                                                                                                    nop
    ldfld     int32 TabDemo.BaseList::count                                                   ldarg.0
                                                                                                                                                                                                    nop
    ldarg.0                                                                                   ldfld     int32 TabDemo.BaseList::count
                                                                                                                                                                                                    ldarg.0
    ldfld     object[] TabDemo.BaseList::items                                                ldarg.0
                                                                                                                                                                                                    ldfld      object[] TabDemo.BaseList::items
    ldlen                                                                                     ldfld     object[] TabDemo.BaseList::items
                                                                                                                                                                                                    ldarg.0
    conv.i4                                                                                   ldlen
                                                                                                                                                                                                    ldfld      int32 TabDemo.BaseList::count
    ceq                                                                                       conv.i4
                                                                                                                                                                                                    ldarg.1
    ldc.i4.0                                                                                  ceq
                                                                                                                                                                                                    stelem.ref
    ceq                                                                                       ldc.i4.0
                                                                                                                                                                                                    ldarg.0
    stloc.1                                                                                   ceq
                                                                                                                                                                                                    dup
    ldloc.1                                                                                   stloc.1
                                                                                                                                                                                                    ldfld      int32 TabDemo.BaseList::count
    brtrue.s IL_0029                                                                          ldloc.1
                                                                                                                                                                                                    dup
    ldarg.0                                                                                   brtrue.s IL_0069
                                                                                                                                                                                                    stloc.2
    ldarg.0                                                                                   ldarg.0
                                                                                                                                                                                                    ldc.i4.1
    ldfld     int32 TabDemo.BaseList::count                                                   ldarg.0
                                                                                                                                                                                                    add
    ldc.i4.1                                                                                  ldfld     int32 TabDemo.BaseList::count
                                                                                                                                                                                                    stfld      int32 TabDemo.BaseList::count
    add                                                                                       ldc.i4.1
                                                                                                                                                                                                    ldloc.2
    call     instance void TabDemo.BaseList::EnsureCapacity(int32)                            add
                                                                                                                                                                                                    stloc.0
    ldarg.0                                                                                   call     instance void TabDemo.BaseList::EnsureCapacity(int32)
                                                                                                                                                                                                    br       IL_0072
    ldfld     object[] TabDemo.BaseList::items                                                ldarg.0
                                                                                                                                                                                                    ldloc.0
    ldarg.0                                                                                   ldfld     object[] TabDemo.BaseList::items
                                                                                                                                                                                                    stloc.s 'Contract.Result<int>()'
    ldfld     int32 TabDemo.BaseList::count                                                   ldarg.0
                                                                                                                                                                                                    br       IL_007a
    ldarg.1                                                                                   ldfld     int32 TabDemo.BaseList::count
                                                                                                                                                                                                    ldarg.0
    stelem.ref                                                                                ldarg.1
                                                                                                                                                                                                    call      instance int32 TabDemo.BaseList::get_Count()
    ldarg.0                                                                                   stelem.ref
                                                                                                                                                                                                    ldloc.3
    dup                                                                                       ldarg.0
                                                                                                                                                                                                    ldc.i4.1
    ldfld     int32 TabDemo.BaseList::count                                                   dup
                                                                                                                                                                                                    add
    dup                                                                                       ldfld     int32 TabDemo.BaseList::count
                                                                                                                                                                                                    ceq
    stloc.2                                                                                   dup
                                                                                                                                                                                                    ldstr      quot;Count == Contract.Old(Count) + 1quot;
    ldc.i4.1                                                                                  stloc.2
                                                                                                                                                                                                    call      void __RewriterMethods::RewriterEnsures$PST0600000B(bool, string)
    add                                                                                       ldc.i4.1
                                                                                                                                                                                                    ldloc.s 'Contract.Result<int>()'
    stfld     int32 TabDemo.BaseList::count                                                   add
                                                                                                                                                                                                    ldloc.s V_4
    ldloc.2                                                                                   stfld     int32 TabDemo.BaseList::count
                                                                                                                                                                                                    ceq
    stloc.0                                                                                   ldloc.2
                                                                                                                                                                                                    ldstr      quot;Contract.Result<int>() == Contract.Old(Count)quot;
    br.s      IL_004b                                                                         stloc.0
                                                                                                                                                                                                    call      void __RewriterMethods::RewriterEnsures$PST0600000B(bool, string)
    ldloc.0                                                                                   br.s      IL_008b
                                                                                                                                                                                                    ldloc.s 'Contract.Result<int>()'
    ret                                                                                       ldloc.0
                                                                                                                                                                                                    ret
  }                                                                                           ret
                                                                                                                                                                                                  }
                                                                                            } // end of method BaseList::Add
Static Contract Checking

 • No silver bullet
    But helps catch errors earliest
    Best used in a focused manner
 • Guides development
    Discovers implicit assumptions
    Propagates assumptions
 • Not only explicit contracts
    Dereferencing null
    Indexing arrays
    Arithmetic exceptions
What Do You Ship?

                              src
                                src
                                  src
                                    src




     Release                                   Contract Reference
    Assemblies                                    Assemblies


                                +         PowerLib.Contracts.d
        PowerLib.dll
                                                   ll


   (minimal runtime checks)                All contracts, no code
Interface Contracts
   <ContractClass(GetType(CloneableContract))> _
   Public Interface ICloneable
    Function Clone() As Object
   End Interface




   ContractClassFor(GetType(ICloneable))> _
   Public Class CloneableContract
      Implements ICloneable
    Public FunctionClone() As Object Implements Icloneable.Clone
      Contract.Ensures( Contract.Result(Of Object>() IsNot Nothing)
      …
    End Function
                                    All classes implementing
   End Class
                                    the interface inherit the
                                    contract
Code Contracts Summary

 • Contract library class enables contracts
   in all .NET languages
    No restrictions on what can be expressed
 • Contracts are being used in the BCL
   today
    Contract library is a core component of .NET 4.0
 • Same contracts used for
    Runtime checking
    Static checking
    Documentation generation
Why People don’t Write Tests

 •   Testing is tedious
 •   Too easy to miss cases
 •   Old tests get stale
 •   Too much legacy code
What The Demo Showed

 • Pex can be used to generate
   comprehensive test suite with high
   code coverage
 • Pex finds contract violations and
   potential error situations
 • The generated test suite integrates
   automatically with
   Visual Studio Team Test
Pex Understands The Code
 • Pex does not generate random inputs,
    enumerate all possible values, or
    make you write test input generators
 • Instead, Pex analyzes your .NET code.
    Test inputs computed by Z3,
    Precise inter-procedural, path-sensitive analysis
 • As a result, you get
   a small test suite with high code coverate
   coverage
Pex Summary

 • Pex generates small test suites with
   high code coverage and bug reports for
   free
 • Reduce test maintenance costs
   by parameterized unit testing
 • Pex has been used in Microsoft
   to test core .NET components
    Almost always finds new bug pathways
Summary

 • Code Contracts for .NET:
   http://research.microsoft.com/Contracts/

 • Pex: test generation for .NET
   http://research.microsoft.com/Pex/
Questions?
• My contact information
   EMail: bjohnson@objectsharp.com
   Twitter: LACanuck
   Blog: http://www.objectsharp.com/blogs/bruce
   MSN: lacanadians@hotmail.com

Weitere ähnliche Inhalte

Was ist angesagt?

Dcom vs. corba
Dcom vs. corbaDcom vs. corba
Dcom vs. corba
Mohd Arif
 

Was ist angesagt? (19)

04 - Qt Data
04 - Qt Data04 - Qt Data
04 - Qt Data
 
Intro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsIntro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and Bindings
 
Devoxx 2012 (v2)
Devoxx 2012 (v2)Devoxx 2012 (v2)
Devoxx 2012 (v2)
 
XMOS XS1 and XC
XMOS XS1 and XCXMOS XS1 and XC
XMOS XS1 and XC
 
The Future of Qt Widgets
The Future of Qt WidgetsThe Future of Qt Widgets
The Future of Qt Widgets
 
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeksBeginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
 
05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics
 
Vaadin7
Vaadin7Vaadin7
Vaadin7
 
Google Dart
Google DartGoogle Dart
Google Dart
 
Dcom vs. corba
Dcom vs. corbaDcom vs. corba
Dcom vs. corba
 
Data Binding in qooxdoo
Data Binding in qooxdooData Binding in qooxdoo
Data Binding in qooxdoo
 
Seastar Summit 2019: Past and future of futures
Seastar Summit 2019: Past and future of futuresSeastar Summit 2019: Past and future of futures
Seastar Summit 2019: Past and future of futures
 
Box2D with SIMD in JavaScript
Box2D with SIMD in JavaScriptBox2D with SIMD in JavaScript
Box2D with SIMD in JavaScript
 
04 Data Access
04 Data Access04 Data Access
04 Data Access
 
Java script Techniques Part I
Java script Techniques Part IJava script Techniques Part I
Java script Techniques Part I
 
Obvious Secrets of JavaScript
Obvious Secrets of JavaScriptObvious Secrets of JavaScript
Obvious Secrets of JavaScript
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
 
One Year of Clean Architecture - The Good, The Bad and The Bob
One Year of Clean Architecture - The Good, The Bad and The BobOne Year of Clean Architecture - The Good, The Bad and The Bob
One Year of Clean Architecture - The Good, The Bad and The Bob
 
Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5
 

Andere mochten auch

Energize Your Business Team Based Strategic Planning Final Doc
Energize Your Business   Team Based Strategic Planning  Final DocEnergize Your Business   Team Based Strategic Planning  Final Doc
Energize Your Business Team Based Strategic Planning Final Doc
redpoint
 

Andere mochten auch (16)

The Fun Page
The Fun PageThe Fun Page
The Fun Page
 
Resume
ResumeResume
Resume
 
Techtrendsellumin Nov09 Abbrev
Techtrendsellumin Nov09 AbbrevTechtrendsellumin Nov09 Abbrev
Techtrendsellumin Nov09 Abbrev
 
Magic + Open Source Fashion
Magic + Open Source Fashion Magic + Open Source Fashion
Magic + Open Source Fashion
 
Introduction to Performance at the Speed of Work
Introduction to Performance at the Speed of WorkIntroduction to Performance at the Speed of Work
Introduction to Performance at the Speed of Work
 
Struttura dello spazio tempo
Struttura dello spazio tempoStruttura dello spazio tempo
Struttura dello spazio tempo
 
Introducing ASP.NET vNext
Introducing ASP.NET vNextIntroducing ASP.NET vNext
Introducing ASP.NET vNext
 
The Performance Puzzle 10 Steps To Unlock Your People With 5 Week Plan V...
The Performance Puzzle   10 Steps To Unlock Your People With 5 Week  Plan   V...The Performance Puzzle   10 Steps To Unlock Your People With 5 Week  Plan   V...
The Performance Puzzle 10 Steps To Unlock Your People With 5 Week Plan V...
 
Setting Your Data Free With OData
Setting Your Data Free With ODataSetting Your Data Free With OData
Setting Your Data Free With OData
 
Think=Pink Iii
Think=Pink IiiThink=Pink Iii
Think=Pink Iii
 
Mc Garry Samples
Mc Garry Samples Mc Garry Samples
Mc Garry Samples
 
Communication Plan
Communication PlanCommunication Plan
Communication Plan
 
Energize Your Business Team Based Strategic Planning Final Doc
Energize Your Business   Team Based Strategic Planning  Final DocEnergize Your Business   Team Based Strategic Planning  Final Doc
Energize Your Business Team Based Strategic Planning Final Doc
 
Paradigmcreated
ParadigmcreatedParadigmcreated
Paradigmcreated
 
Biodiversity of himalaya final
Biodiversity of himalaya finalBiodiversity of himalaya final
Biodiversity of himalaya final
 
Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQUnit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
 

Ähnlich wie Code Contracts In .Net

Eclipse Code Recommenders @ MAJUG 2011
Eclipse Code Recommenders @ MAJUG 2011Eclipse Code Recommenders @ MAJUG 2011
Eclipse Code Recommenders @ MAJUG 2011
Marcel Bruch
 
T-121-5300 (2008) User Interface Design 10 - UIML
T-121-5300 (2008) User Interface Design 10 - UIMLT-121-5300 (2008) User Interface Design 10 - UIML
T-121-5300 (2008) User Interface Design 10 - UIML
mniemi
 

Ähnlich wie Code Contracts In .Net (20)

Introduction to Functional Programming with Scheme
Introduction to Functional Programming with SchemeIntroduction to Functional Programming with Scheme
Introduction to Functional Programming with Scheme
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-x
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgeChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
 
Eclipse Code Recommenders @ cross-event Deutsche Telekom Developer Garden Tec...
Eclipse Code Recommenders @ cross-event Deutsche Telekom Developer Garden Tec...Eclipse Code Recommenders @ cross-event Deutsche Telekom Developer Garden Tec...
Eclipse Code Recommenders @ cross-event Deutsche Telekom Developer Garden Tec...
 
MongoDB Live Hacking
MongoDB Live HackingMongoDB Live Hacking
MongoDB Live Hacking
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
The CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitThe CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGit
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer development
 
Zero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youZero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for you
 
Eclipse Code Recommenders @ MAJUG 2011
Eclipse Code Recommenders @ MAJUG 2011Eclipse Code Recommenders @ MAJUG 2011
Eclipse Code Recommenders @ MAJUG 2011
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
T-121-5300 (2008) User Interface Design 10 - UIML
T-121-5300 (2008) User Interface Design 10 - UIMLT-121-5300 (2008) User Interface Design 10 - UIML
T-121-5300 (2008) User Interface Design 10 - UIML
 
What is the ServiceStack?
What is the ServiceStack?What is the ServiceStack?
What is the ServiceStack?
 
Tdd with python unittest for embedded c
Tdd with python unittest for embedded cTdd with python unittest for embedded c
Tdd with python unittest for embedded c
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition Software
 
Data Types/Structures in DivConq
Data Types/Structures in DivConqData Types/Structures in DivConq
Data Types/Structures in DivConq
 
Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみた
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

Code Contracts In .Net

  • 1. Putting a Hit on Bugs with Code Contracts
  • 2. Software needs Reliability • Two Components  Correctness • Does what it’s supposed to do and only that  Robustness • Acts appropriately in cases where it cannot do what it is supposed to do
  • 3. But What’s it Supposed to Do?
  • 4. Describing Software • How do developers express what software is supposed to do? A. Write it in English, allowing your users/clients to approve it beforehand? B. Write it in the comments? C. Describe it in a format system based on discrete mathematics D. Poorly? E. All of the above?
  • 5. Correctness of a Routine • State the conditions that must be true before the routine can work correctly  Pre-conditions • State the conditions that will be true after execution, if the routine has worked correctly  Post-conditions
  • 6. Let’s Consider an Example • Create a class that implements a time of day  Exposes hour, minute, second properties  Implementation could be as three separate integers or as the number of seconds since midnight • We’re going to look only at the process of assigning the hour
  • 7. Contracts • Document assumptions  Preconditions, postconditions, invariants • Are executable  Can perform checks at run-time • Help with static verification  Assist with early error detection  Can be used by tools to generate test cases • Different than assertions  Assertions are not viewed as a contract, they are a suggestion  Difficult to use with test case generation tools
  • 8. What Contracts Can I Write? • Requires  What must be true at method entry • Ensures  What must be true at method exit  Includes exits on exceptions • Invariants  What must be true at all method exits • Assertions  What must be true at a particular point • Assumptions  What should be true at a particular point
  • 9. What Can I Put In A Contract? • Any boolean expression  In your favorite programming language!  Including method calls (but must be marked Pure) • Contract.Result  refer to the return value of the method • Contract.OldValue  refer to values at method entry • Quantifiers  Contract.ForAll(0,A.Length, Function(i) A(i) > 0);  Contract.Exists(0,A.Length, Function(i) A(i) > 0);
  • 10. Public Overridable Function Add(value As Object) As Integer{ Contract.Requires( value IsNot Nothing ) Contract.Ensures( Count = Contract.OldValue(Of Integer)(Count) + 1 ) Contract.Ensures( Contract.Result(Of Integer)() = _ Contract.OldValue(Of Integer)(Count) ) Executable Runtime Contract Checking if (_size == _items.Length) EnsureCapacity(_size+1); _items[_size] = value; .method public hidebysig newslot virtual instance int32 Add(object 'value') cil managed { .locals init (int32 'Contract.Old(Count)', return _size++; int32 'Contract.Result<int>()') ldarg.0 call instance int32 TabDemo.BaseList::get_Count() } stloc.3 ldarg.1 ldnull csc/vbc/… ceq ldc.i4.0 .method public hidebysig newslot virtual instance int32 Add(object 'value') cil managed ceq { ldstr quot;value != nullquot; ldarg.1 call void __RewriterMethods::RewriterRequires$PST06000009(bool, string) ldnull /d:CONTRACTS_FULL Release ldarg.0 ceq ldfld int32 TabDemo.BaseList::count ldc.i4.0 ldarg.0 ceq ldfld object[] TabDemo.BaseList::items call void [Microsoft.Contracts]Microsoft.Contracts.Contract::Requires(bool) Compile ldlen ldarg.0 conv.i4 call instance int32 TabDemo.BaseList::get_Count() csc/vbc/… ceq ldarg.0 ldc.i4.0 call instance int32 TabDemo.BaseList::get_Count() ceq call !!0 [Microsoft.Contracts]Microsoft.Contracts.Contract::Old<int32>(!!0) stloc.1 ldc.i4.1 ldloc.1 add brtrue IL_004d ceq nop call void [Microsoft.Contracts]Microsoft.Contracts.Contract::Ensures(bool) ldarg.0 call !!0 [Microsoft.Contracts]Microsoft.Contracts.Contract::Result<int32>() ccrewrite ldarg.0 ldarg.0 ldfld int32 TabDemo.BaseList::count call instance int32 TabDemo.BaseList::get_Count() ldc.i4.1 .method public hidebysig newslot virtual instance int32 Add(object 'value') cil managed call !!0 [Microsoft.Contracts]Microsoft.Contracts.Contract::Old<int32>(!!0) add { ceq call instance void TabDemo.BaseList::EnsureCapacity(int32) ldarg.0 call void [Microsoft.Contracts]Microsoft.Contracts.Contract::Ensures(bool) nop ldfld int32 TabDemo.BaseList::count ldarg.0 nop ldarg.0 ldfld int32 TabDemo.BaseList::count ldarg.0 ldfld object[] TabDemo.BaseList::items ldarg.0 ldfld object[] TabDemo.BaseList::items ldlen ldfld object[] TabDemo.BaseList::items ldarg.0 conv.i4 ldlen ldfld int32 TabDemo.BaseList::count ceq conv.i4 ldarg.1 ldc.i4.0 ceq stelem.ref ceq ldc.i4.0 ldarg.0 stloc.1 ceq dup ldloc.1 stloc.1 ldfld int32 TabDemo.BaseList::count brtrue.s IL_0029 ldloc.1 dup ldarg.0 brtrue.s IL_0069 stloc.2 ldarg.0 ldarg.0 ldc.i4.1 ldfld int32 TabDemo.BaseList::count ldarg.0 add ldc.i4.1 ldfld int32 TabDemo.BaseList::count stfld int32 TabDemo.BaseList::count add ldc.i4.1 ldloc.2 call instance void TabDemo.BaseList::EnsureCapacity(int32) add stloc.0 ldarg.0 call instance void TabDemo.BaseList::EnsureCapacity(int32) br IL_0072 ldfld object[] TabDemo.BaseList::items ldarg.0 ldloc.0 ldarg.0 ldfld object[] TabDemo.BaseList::items stloc.s 'Contract.Result<int>()' ldfld int32 TabDemo.BaseList::count ldarg.0 br IL_007a ldarg.1 ldfld int32 TabDemo.BaseList::count ldarg.0 stelem.ref ldarg.1 call instance int32 TabDemo.BaseList::get_Count() ldarg.0 stelem.ref ldloc.3 dup ldarg.0 ldc.i4.1 ldfld int32 TabDemo.BaseList::count dup add dup ldfld int32 TabDemo.BaseList::count ceq stloc.2 dup ldstr quot;Count == Contract.Old(Count) + 1quot; ldc.i4.1 stloc.2 call void __RewriterMethods::RewriterEnsures$PST0600000B(bool, string) add ldc.i4.1 ldloc.s 'Contract.Result<int>()' stfld int32 TabDemo.BaseList::count add ldloc.s V_4 ldloc.2 stfld int32 TabDemo.BaseList::count ceq stloc.0 ldloc.2 ldstr quot;Contract.Result<int>() == Contract.Old(Count)quot; br.s IL_004b stloc.0 call void __RewriterMethods::RewriterEnsures$PST0600000B(bool, string) ldloc.0 br.s IL_008b ldloc.s 'Contract.Result<int>()' ret ldloc.0 ret } ret } } // end of method BaseList::Add
  • 11. Static Contract Checking • No silver bullet  But helps catch errors earliest  Best used in a focused manner • Guides development  Discovers implicit assumptions  Propagates assumptions • Not only explicit contracts  Dereferencing null  Indexing arrays  Arithmetic exceptions
  • 12. What Do You Ship? src src src src Release Contract Reference Assemblies Assemblies + PowerLib.Contracts.d PowerLib.dll ll (minimal runtime checks) All contracts, no code
  • 13. Interface Contracts <ContractClass(GetType(CloneableContract))> _ Public Interface ICloneable Function Clone() As Object End Interface ContractClassFor(GetType(ICloneable))> _ Public Class CloneableContract Implements ICloneable Public FunctionClone() As Object Implements Icloneable.Clone Contract.Ensures( Contract.Result(Of Object>() IsNot Nothing) … End Function All classes implementing End Class the interface inherit the contract
  • 14. Code Contracts Summary • Contract library class enables contracts in all .NET languages  No restrictions on what can be expressed • Contracts are being used in the BCL today  Contract library is a core component of .NET 4.0 • Same contracts used for  Runtime checking  Static checking  Documentation generation
  • 15. Why People don’t Write Tests • Testing is tedious • Too easy to miss cases • Old tests get stale • Too much legacy code
  • 16. What The Demo Showed • Pex can be used to generate comprehensive test suite with high code coverage • Pex finds contract violations and potential error situations • The generated test suite integrates automatically with Visual Studio Team Test
  • 17. Pex Understands The Code • Pex does not generate random inputs,  enumerate all possible values, or  make you write test input generators • Instead, Pex analyzes your .NET code.  Test inputs computed by Z3,  Precise inter-procedural, path-sensitive analysis • As a result, you get a small test suite with high code coverate coverage
  • 18. Pex Summary • Pex generates small test suites with high code coverage and bug reports for free • Reduce test maintenance costs by parameterized unit testing • Pex has been used in Microsoft to test core .NET components  Almost always finds new bug pathways
  • 19. Summary • Code Contracts for .NET: http://research.microsoft.com/Contracts/ • Pex: test generation for .NET http://research.microsoft.com/Pex/
  • 20. Questions? • My contact information  EMail: bjohnson@objectsharp.com  Twitter: LACanuck  Blog: http://www.objectsharp.com/blogs/bruce  MSN: lacanadians@hotmail.com