Unit testing is done to validate a piece of code. Developers use unit tests to test a unit of code and to improve code quality. Code Contracts complement unit testing. It was introduced by Microsoft in .NET framework 4. The contracts take form of pre-conditions, post-conditions and object invariants for the classes. Code contracts provides feedback as code is written. It gives useful information about the code being develop. These help in ensuring software correctness in three ways:

They are part of the method implementation and contribute to ensuring the function abides by its contract. Second they force developers to think about what each method if expected to do and why. Finally contracts are form of metadata and the information they convey can be consumed by other code analysis tools like Microsoft static checker. The static checker is triggered by code changes, compile steps and ensures that pre-conditions and post-conditions match. It also ensures that conditions that must hold for a class at all times is always met.

If the contract defined for the classes are correct and no warnings are generated from static analysis then the code is likely to be correct. Correctness refers to the correct flow of actions and data which contracts can verify. Implementation details are verified with unit tests. Unit tests and code contracts complement each other.

Reference for this blog post has been taken from Information Week magazine.