Code Contracts & Exception throwing difference
public static string TrimAfter(string value, string suffix)
{
// <pex>
Contract.Requires(suffix != (string)null);
Contract.Requires
(value.IndexOf(suffix) >= 0 && value.Length >= value.IndexOf(suffix));
Contract.Requires(value != (string)null);
// </pex>
int index = value.IndexOf(suffix);
if (index < 0)
return value;
return value.Substring(0, index);
}
I called this method with nulls arguments and it was compiled. So it is not clear for me why it is better开发者_如何学Python then throwing Exceptions. Could you guys explain me if Code Contracts really has any additional features? :) Thanks in advance.
In addition to other points made, contracts can be applied to interfaces (you couldn't do that with regular exceptions) and are enforced through inheritance (something else you'd be very hard pressed to do with regular exceptions).
- Depending on your edition of VS(Premium or Ultimate if I remember correctly) you can get compile-time checking.
The problem with this it is quite a bit of work to make the static checker happy. And I'm not sure if it's worth the effort for most programs. But perhaps a restricted subset such as null-checks could work well. - It's possible to automatically generate documentation from it.
- It's shorter code, making people more likely to use it.
The main point for me. I'm lazy and if writing checks gets easier I'm more likely to add additional checks. In particual I found the old style argument null checks a bit verbose. - You can specify an exception if you want, so you get the same outward behavior as with the old checks.
On the other hand it shouldn't be hard to parse the IL recognizing the old standard pattern for pre-condition checks and use that generate documentation.
To not let it compile, you need the premium edition of code contracts with static checker: http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx
I'm going to guess but, from the docs:
A Visual Studio add-in lets you specify the level of code contract analysis to be performed. The analyzers can confirm that the contracts are well-formed (type checking and name resolution) and can produce a compiled form of the contracts in Microsoft intermediate language (MSIL) format. Authoring contracts in Visual Studio lets you take advantage of the standard IntelliSense provided by the tool.
Tools are available here.
精彩评论