Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use code contracts in .NET 4.0 without making my code look cluttered?

I have started using Code Contracts and have found that it makes it difficult to immediately spot the 'guts' of a method.

Take this (very simple) example:

public static void UserAddNew(string domain, string username, string displayName)
{
    Contract.Assert(!string.IsNullOrWhiteSpace(domain));
    Contract.Assert(!string.IsNullOrWhiteSpace(username));
    Contract.Assert(!string.IsNullOrWhiteSpace(displayName));

    LinqDal.User.UserAddNew(domain, username, displayName);
}

Now I'm tempted to put the contracts in a region, so that they can be hidden away, but then I'm concerned that I'm losing a nice advantage of being able to glance at the method and see what it expects.

What do you do to keep your contracts 'tidy'? Or am I just being too picky?

like image 893
Fiona - myaccessible.website Avatar asked Feb 15 '11 08:02

Fiona - myaccessible.website


People also ask

What is precondition C#?

Preconditions specify state when a method is invoked. They are generally used to specify valid parameter values. All members that are mentioned in preconditions must be at least as accessible as the method itself; otherwise, the precondition might not be understood by all callers of a method.

Which of the following are benefits of code contracts?

Improved testing: Code contracts provide static contract verification, runtime checking, and documentation generation. Automatic testing tools: You can use code contracts to generate more meaningful unit tests by filtering out meaningless test arguments that do not satisfy preconditions.

What are contracts in programming?

Contracts enable specifying conditions that must hold true when the flow of runtime execution reaches the contract. If a contract is not true, then the program is assumed to have entered an undefined state. Rationale: Building contract support into the language provides: a consistent look and feel for the contracts.


1 Answers

Have a look at the ContractClass and ContractClassFor attributes. This allows you to write classes with the code contracts in separate assemblies. This allows you to have the contracts available for dev work, doesn't clutter your code and also means you don't have to deploy the contracts with the live code:

Contract Class Attribute

Contract Class For Attribute

like image 100
Ray Booysen Avatar answered Sep 17 '22 11:09

Ray Booysen