How to use methods contracts and why?

5

Reading a book on .NET development, I saw a brief description of methods contracts and tried to find out a bit more on the internet.

  

It uses an imperative syntax that is costly and has low tool support. To use the contract in the library and in the application, you must perform a post-compilation process. Overall, it is an interesting project, but it needs a first-class compiler and support syntax to be useful.

I found something related to the following code:

public int Insert(T item, int index)
    requires index >= 0 && index <= Count
    ensures return >= 0 && return < Count
{ … }

On the internet, I've also seen that you have very little content about it, and would like to know what it is, and if it's really worth using?

    
asked by anonymous 05.12.2018 / 11:03

1 answer

5

This syntax does not exist. There's a proposal for it to go into C #, and I'm very keen to get in.

Today there is a contract library that does something similar but is rather inferior. The use of contracts exists since .NET 4.0.

Using it along with static analysis tools can be powerful, and in fact helps. I'm not sure why, but newer versions of Visual Studio no longer have the tools, and the mechanism has become less useful unless you do a lot of things manually or on your own.

It does not mean that it has not yet been used, but it is not very different from a if , at most it becomes more semantic. Anyway to be a first class engine needs to be in the language and the compiler will collaborate.

Contracts can be more interesting than typical engines because they can be resolved at compile time and can even be eliminated from the code by becoming run-time cost-free. Implemented in the right way can become part of the contract of the type and method, that is, whoever calls it should respect the contract directly. And in sophisticated mechanisms this can be propagated and until only the input of the data is verified if it is within the contract eliminating all other checks because the data already is valid (this is ideal, it is not simple to make it work in the language) / p>

I like your use, but I admit its current state. NET is not so advantageous as well, but it's also not too bad to avoid it. At the very least it gives more semantics and can easily change afterwards if the engine is improved.

I'm still trying to figure out why they are no longer emphasized. But the .NET code uses a lot, I think everyone should use more. It helps give you more robustness and legibility.

Wikipedia article about general use.

I answered something about them in Is there any similar functionality to Assert (assertions) in C #? .

    
05.12.2018 / 11:40