DCSIMG
How to write better code with Code contracts PEX and Moles - Manu Cohen-Yashar's Blog

Manu Cohen-Yashar's Blog

How to write better code with Code contracts PEX and Moles

When I write code I always ask myself how can I make it better.

One of the main steps I take to improve my code is write unit tests and use Asserts.

All Code is based on assumptions. (i.e. a variable is not null etc). These assumptions must be validated before the code is executed. We all know that and I hope you all do that but still it happens my that code crushes because an assumption I forgot was not validated. I was looking for something to help be to improve my code and then I heard about PEX.

PEX is an infrastructure for unit test automatic generation based on the code you write.

PEX is a separate download which should be installed. Now all you have to do is simply write your code, right click the project and choose "Run PEX"

image

PEX will analyze your code and create parametric unit test which will test all the possible code path.

Let us take a very simple example:

    public class Class1

    {

        public int Calc(int a, int b)

        {

            if (a == 0)

                throw new ArgumentException();

            if (a > 2)

                return a + b;

 

            return a - b;

        }

    }

Visual studio allows to see the tests and their results

 image

 image  

The  test  can  saved into a test project and integrated in the CI

PEX is so simple to use yet it is extremely powerful. Using PEX I find so many cases I did not handle and my code quality improves.

Assumption validation was traditionally done using a simple if statement and if it was found not valid an exception was thrown.

Code contracts introduced with framework 4.0 (it is possible to use code contracts in framework 3.5 but the assembly Microsoft.Contracts has to be referenced) allows validating assumptions better. For example:  Contract.Requires(a != 0);

If a code contract is validated an exception is thrown.

PEX understand code contracts and the tests it will create takes the contracts into consideration.

Automatic help and documentation tools can understand code contracts as well and publish the contract into the public API documentation.

To summarize PEX and Code contracts are simple to use yet they improve our code quality dramatically.

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: