Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Code contracts

  • Login to see the comments

  • Be the first to like this

Code contracts

  1. 1. Design by Contract for Mainstream .NET<br />Code Contracts<br />AshicMahtab<br />
  2. 2.
  3. 3. Static Languages<br />Why do we code in C#?<br />So type errors don’t manifest at runtime?<br />Intellisense?<br />Fear of learning Ruby?<br />
  4. 4. Contract<br />A promise that something will behave in a certain way.<br />(Sounds like an interface, right?)<br />
  5. 5. A joint account can be opened only if the number of holders is greater than two.<br />public void OpenJointAccount(AccountHolder[] holders)<br />An account holder’s balance may never fall below -100.<br />Go ahead…try writing interfaces for them.<br />
  6. 6. Design by Contract<br />Based on the work of Alan Turing, Tony Hoare, EdsgerDijkstra, David Gries<br />Popularized / advocated by Bertrand Meyer and originally implemented in Eiffel.<br />Works on the basis of constraints like preconditions, post conditions and invariants which the supplier provides.<br />
  7. 7. Preconditions: I require this to be true before I execute.<br />Post condition: I ensure this to be true when I am done executing.<br />Invariant: A condition that holds true during the lifetime of an object. It may not hold during the execution of a method but will do so before and after the method executes.<br />
  8. 8. Demo<br />Basics<br />Preconditions, Post conditions, Invariants<br />Subtle edge case violations<br />Contract Blocks, [Pure]<br />Contracts on Interfaces and Abstract Classes<br />[ContractArgumentValidator], [ContractAbbreviator]<br />
  9. 9. Integrating into legacy apps<br />[ContractVerification(false)]<br />Baseline<br />
  10. 10. Drawbacks<br />Slower build with static checking<br />Public properties <br />Interface contracts have weird syntax<br />Currently no contracts on delegates<br />Static checker can’t understand collections<br />Algorithmic performance may be compromised<br />IL mangling…no edit and continue<br />Must have buy in – something whole team uses or nobody does<br />
  11. 11. Resources<br /><br />