Add some simplicity to Contract.
-
Monday, April 16, 2012 9:17 AM
Hello!
Code Contracts is a really cool feature.
Long time ago I used such constructions as Guard.Verify(); Which implements contract verification in realtime.
Now I try to use Contracts.
And got some "issue" which is not an issue but some kind of dissatisfaction:
I'm layzy developer and earlier I used to see constructions like that:
Guard.VerifyArgumentNotNull(arg,"arg");
or
_member = Guard.EnsureArgumentNotNull(arg,"arg");
but now I need to write:Contract.Verify(arg!=null, "arg");
_member = arg;Why not to add several helpfull members which slightly reduces amount of code?
This can be checking for strings, enumerations. Some help for developers.
What do you think about that?
Thanks!
All Replies
-
Monday, April 16, 2012 8:06 PM
Hi,
This has been requested before.
Basically, the reason why the CC team isn't going to add these kinds of abbreviated contracts into CC is because CC is designed to be a contract platform, not a contract library. In other words, it provides the tools that you need to define contracts yourself.
You've got some options. In recommended (IMO) order:
- Use code snippets. For example, type crn and then press tab. (It stands for
Contract Requires Not/Null). It expands to the following code and places the cursor at the | position.
Contract.Requires(| != null);
There are several other useful snippets as well. Go to Tools > Code Snippets Manager... > Language = Visual C# > Code Contract Snippets.
The benefit to using code snippets over custom abbreviators for things like non-null checks is that Contract.Requires(arg != null) and Contract.Ensures(Contract.Result<T>() != null) are standard. This will help other static analysis tools, extensions and editor extensions to easily take advantage of your contracts in the future. It also makes your code easier to understand and maintain when new developers join your team (presuming they're already familiar with CC). - Define abbreviator methods yourself, depending upon what you need. See ContractAbbreviatorAttribute §2.12 in the
Contracts User Manual. Note that the attribute is now defined in .NET 4.5, but you'll have to import it for .NET 4.0 and earlier. See the manual for details.
public static class Contract2 { [ContractAbbreviator] public static void RequiresNotNull(object arg) { Contract.Requires(arg != null); } }
- Dave
- Edited by Dave Sexton Monday, April 16, 2012 8:15 PM Renamed IsNotNull to RequiresNotNull; some re-formatting.
- Use code snippets. For example, type crn and then press tab. (It stands for
Contract Requires Not/Null). It expands to the following code and places the cursor at the | position.

