As probably some of you know, code contracts concept is very nice. It allows on checking if the rules we need are fulfilled thanks to which we could sleep safely. First time it was introduced in Eiffel language, you could read more on that on Design by Contract Wikipedia page. Looking through Wikipedia page, we could find:
“Design by contract (DbC), […] is an approach for designing software. It prescribes that software designers should define formal, precise and verifiable interface specifications for software components, which extend the ordinary definition of abstract data types with preconditions, postconditions and invariants.”
Wait for a moment, isn’t that matching to our concept of unit testing? Just think about that:
- in both cases we want to check for assertions
- for both we want to be sure that tests will fail if condition is not fulfilled
The big benefit is that you separate concepts of checking if your code is fulfilling contract in your unit tests, avoiding frequent usage of checks in runtime which could impact your performance.
Personally, having that in mind I cannot find real value of Code Contracts that Microsoft has created, still spending money on that. I don’t believe it could replace unit tests anyway, just being addition to that. On the other hand, I believe unit tests could replace code contacts easily allowing developers on good sleep all the time 🙂