Code contracts - should confidential methods be checked for before and after conditions?

I am trying to speed up the execution of code contracts. I like this concept, but in practice I don't see the value of adding Contract.Requires to numerous private methods, some of which are just a string or two long.

I see a point in public methods, but according to the methods of a private class, it seems like it's overkill.

+7
source share
2 answers

The main reason you want to apply contracts to private methods is to use static analysis. You often write code that makes implicit assumptions about your private methods (this method never returns null, for example), and a static proxy will tell you that. You can then either place this assumption in the body of your public method, or add it as a private method contract. The latter, as a rule, is cleaner because it allows reusing the assumption implied by the contract in many applications of this particular method.

Personally, I refused the code contracts until he had a chance to mature yet. The syntax is inconvenient (we really need a simple representation for non-zero parameters in particular), and you can go through a lot of loops trying to make static proofs complex systems. This is a very good idea, though, and I think it's just a matter of time until proper contract support for complex static analysis flowed into .NET (actual CIL metadata), with native language support in C #, and not fixed as inconvenient expansion.

Otherwise, I believe that it is very important to go through the process of applying contracts to a small application from top to bottom, including private and public methods. As you work on how all this proves, it reveals the many implicit assumptions you make every day without even realizing it. You also often find cases of failures that you never considered, because the thinking that you cultivate when developing contracts emphasizes the points at which you make assumptions, and encourages you to consider whether your assumptions can sometimes be made. I don’t have time for a schedule to do this in my daily work, but I definitely learned a lot from the period when I experimented with code contracts.

+10
source

Contracts are usually checked only before / after public methods. Private methods are called only part of the call to the public method, so they do not need to be checked separately.

http://en.wikipedia.org/wiki/Class_invariant

+1
source

All Articles