Wednesday, November 14, 2012

Design by Contract Programming


Allows specification of pre-conditions, post-conditions, and object invariants. Contracts act as checked documentation of your external and internal APIs.

Assembly Reference: Microsoft.Contracts.Library
Namespace: System.Diagnostics.Contracts

Turning on Runtime Checking

Project Propertes | Code Contracts | Perform Runtime Contract Checking

Precondition becomes Debug.Assert()

Project Propertes | Code Contracts | Perform Static Contract Checking

Examples

// Requires - Pre-Condition
// cr <tab> <tab>
Contract.Requires(denom > 0);   // placed at the beginning of the method (pre-condition)

// Object Invariant
// Creating Object Invariant shortcut: cim <tab> <tab>
[ContractInvariantMethod]
protected void ObjectInvariant() {
  Contract.Invariant(this.denom > 0);
// make this hold true all the time, not just where required is used
// Checked at end of every public method
}

// Ensure what is returned from a method
// Post-Condition
// ce <tab> <tab> for ensures
// cr <tab> <tab> for result
Contract.Ensures(Contract.Result<int>() >= 0); // added at the beginning of a method

Reference: http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx