8

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?

Fiona - myaccessible.website
  • 14,481
  • 16
  • 82
  • 117
  • possible duplicate of: "How do I add new features to my application without making my code look cluttered?" – Cody Gray - on strike Feb 15 '11 at 08:49
  • 3
    AFAICT, this is not new or specific to Code Contracts – the method was checking the parameters even before CC, wasn’t it? I don’t have any solution to this apart from a bit of whitespace… – Mormegil Feb 15 '11 at 08:59
  • I agree with Mormegil. Before CC you were supposed to write "if(condition) throw new argumentexception". – koenmetsu Feb 15 '11 at 09:48
  • 1
    Just a related note, it would make more sense to use Contract.Requires() instead of Contract.Assert() here. Makes a difference in the calling code. – H H Apr 27 '11 at 17:52

1 Answers1

6

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

Ray Booysen
  • 28,894
  • 13
  • 84
  • 111
  • 1
    True, but that won't work on the static method he used in his example. – koenmetsu Feb 15 '11 at 09:54
  • 1
    Also: deploying the contracts depends on what settings you use in the Code Contracts Property Pane. Just not deploying the Contracts without the right settings will just give you trouble. – koenmetsu Feb 15 '11 at 12:48
  • I'd assume the developer would read the documentation about how to use the feature. :) – Ray Booysen Feb 15 '11 at 13:37