I start to use C# Code Contracts with enabled static and runtime checks. The problem is that some code contract checks may be duplicated from method to method and I see no good way to avoid this.
My hope is to avoid static analyzer warnings at all and don't suppress it if possible.
Lets consider the example:
There are following simple classes. This is an usual example of business logic model classes:
class Category
{
public string Name { get; set; }
}
class Article
{
public string Title { get; set; }
public string Content { get; set; }
public Category Category { get; set; }
}
For some reflection-based techniques (like model binding in MVC, database mapping) we need to provide public default constructor and public setters for model properties. So we can't guarantee that for example for Category the Contract.Invariant(!string.IsNullOrEmpty(Name)) is always true.
Then we create the next method in our internal CategoryRepository class. We assume that all validation passed earlier and accept only valid categories:
public void Add(Category category)
{
Contract.Requires(category != null);
Contract.Requires(!string.IsNullOrEmpty(category.Name));
...
}
So far so good. Then we add similar method to ArticleRepository:
public void Add(Article article)
{
Contract.Requires(article != null);
Contract.Requires(!string.IsNullOrEmpty(article.Title));
Contract.Requires(!string.IsNullOrEmpty(article.Content));
Contract.Requires(article.Category != null);
Contract.Requires(!string.IsNullOrEmpty(article.Category.Name));
...
}
The problems are:
1) In every place where we expect a valid Category by contract we need to duplicate checks like:
Contract.Requires(category != null);
Contract.Requires(!string.IsNullOrEmpty(category.Name));
Sometimes we also need to make these checks in Contract.Assume methods.
2) External classes (like Article) should make checks for contracts of Category class. Looks like violation of LoW and basic encapsulation principles.
I tried next solutions:
1) Extract duplicated code to pure method in Category class like this:
[Pure]
public static bool Valid(Category category)
{
if (category == null)
return false;
return !string.IsNullOrEmpty(category.Name);
}
and the use contract this way:
Contract.Requires(Category.Valid(category));
Not very good solution and also it doesn't work - the static analyzer is not satisfied.
2) Define an invariant for Category:
[ContractInvariantMethod]
void Invariant()
{
Contract.Invariant(!string.IsNullOrEmpty(Name));
}
This solution is quite good and allow to remove unnecessary checks out of Category class, but actually this invariant is no valid (e.g. in default constructor). And static analyzer correctly detects this violation.
Am I doing something wrong and there is a more convenient way to use Code Contracts with static analyzer?