.Net Code Contracts - Where to learn more? [closed]

烂漫一生 提交于 2019-11-30 04:54:58

Code Contracts were introduced in .NET 4.0 and they provide a language-agnostic method to express coding assumptions in programs.

They basically allow you to check for pre-conditions, post-conditions and other features and can greatly improve the testing process and the eventual quality of code that is being written.

From Microsoft:  

  • Runtime Checking. Our binary rewriter modifies a program by injecting    the contracts, which are checked as part of program> execution. Rewritten programs improve testability: each contract acts as an oracle, giving a test run a pass/fail indication. Automatic testing tools, such as Pex, take advantage of contracts to generate more meaningful unit tests by filtering out meaningless test arguments that don't satisfy the pre-conditions. 

  • Static Checking. Our static checker can decide if there are any contract violations without even running the program! It checks for implicit contracts, such as null    dereferences and array bounds, as well as the explicit contracts.

  • Documentation Generation. Our documentation generator augments existing XML doc files with contract information. There are also new style sheets that can be used with Sandcastle so that the generated documentation pages have contract sections.

Learn More:

Code Contracts are a relatively new way of performing checks on input and output of functions. Where they differ from your standard Assert type checking is that the generated IL that checks input checks it directly prior to the function being called, and the code that checks output, after your function has actually exited.

Why is this useful?

Well, it prevents you modifying the variables after you think your function may return, thereby potentially introducing bugs.

Here's an example.

public void doSomething(SomeObject foo)
{
    Contract.Requires<ArgumentNullException>(foo != null);
}

Now, Code Contracts require that there be no code before that check. In the generated IL, the value of foo is tested PRIOR to the call. It's a sure-fire way of ensuring that your input is as expected.

The other, is the Contract.Ensures construct. This is basically like Requires but operates on your return value.

public int doSomethingElse()
{
    Contract.Ensures(Contract.Result<int>() != 0);
    int ret = 1;
    return ret;
}

This would be particularly useful if you had multiple exit paths from your function...

public int someBadFunction()
{
    Contract.Ensures(Contract.Result<int>() != 0);
    if(....)
    {
       if(....) return 2;
       if(....) return 8;
    }
    return 3;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!