Friday, January 27, 2012

Another case for code contracts

I stumbled upon one of the many articles on inversion of control (IoC). Interesting enough, one of the arguments the author used for utilizing interfaces was that it enabled you to safely change the actual implementation of the interface later on. I have to disagree on that point. In fact, in some way I think that depending upon a specific class rather than an interface is more 'honest'. Not saying that you shouldn't use interfaces: interfaces, combined with IoC,  are very useful. One issue I have with many interfaces is that they are not defined in terms of pre-conditions, post-conditions and invariants. Without a contract you can still only guess what the interface provides to you. If you rely upon a specific class, you at least recognize that you are dependent upon the implementation details of that class. When you rely upon an interface without a contract, you are basically saying "I rely upon an interface that has no clear specification, but I trust anyone that implements it not to violate my interpretation of the interface." Code contracts are crucial for well defined interfaces.

On a related note: during the "meet the experts" session at the Windows Build conference I talked to some Microsoft employees about model checking. Their first reaction was, with a somewhat surprised look: "Do you develop driver software?" My answer was "Nope", but it was a clear indication that formal methods are still only generally accepted in very small pockets of our industry. Maybe over the next couple of years Microsoft will finally be able to make some of these formal methods readily available to all programmers.

No comments:

Post a Comment