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

廉价感情. 提交于 2019-12-14 00:19:40

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/5001356/how-do-i-use-code-contracts-in-net-4-0-without-making-my-code-look-cluttered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!