Wednesday, May 16, 2012

Code Contract : A Design by contract programming

Code contracts are used to define preconditions, postconditions and object invariants in a particular piece of code. These conditions are defined as contracts which will see below.

They let you specify a pass/fail condition for your application within code, which indirectly helps you in writing more meaningful unit tests without worrying about data and its context.

You con download dlls required for code contracts from this location.

Contracts are expressed using static method calls at method entries. Tools take care to interpret these declarative contracts in the right places. These methods are found in the System.Diagnostics.Contracts namespace.

• Contract.Requires takes a boolean condition and expresses a precondition of the method. A precondition must be true on entry to the method. It is the caller's responsibility to make sure the pre-condition is met.

• Contract.Ensures takes a boolean condition and expresses a postcondition of the method. A
postcondition must be true at all normal exit points of the method. It is the implementation's responsibility that the postcondition is met.

 After you have downloaded above installer and installed on your machine, you can open your project and open Properties tab in your application and select Contract tab as shown below.


Here you select "Perform Runtime Checking" & "Contract Reference Assembly" as Build as shown in following image.


 Now you are ready to use all contract methods, in our code sample I am going to show how we make sure that user enters a number which is greater than Zero. In my code sample I am calculating Factorial for a passed number and before I calculate Factorial I need to make sure that user enters a number which is grater than Zero. Here we can see code execution fails when user enters number which is zero.


Now, when we disassemble generated exe, we can see that application when Builds, it inject a class "__ContractsRuntime" under System.Diagnostic.Contracts namespace , this class implementation is shown in following image.

And when we see our disassembled code it looks like, it injects __ContractsRuntime.Requires method which executes condition which was specified earlier.









No comments:

Post a Comment