开发者

Checking preconditions in .NET

I'm a fan of the "fail early"开发者_运维问答 strategy and want to check that methods params have correct values for example. In Java I'd use something like Guava:

checkArgument(count > 0, "must be positive: %s", count);

Is there something similar for .NET?


What you want to do is Design By Contract.

You should use Code Contracts for defining contracts i.e. Preconditions, post-conditions and invariants for your types\methods in C#.

IMO the best and most comprehensive coverage of code-contracts is here.


Code contracts: http://msdn.microsoft.com/en-us/devlabs/dd491992


Code Contracts are still an add on/not part of the standard Visual Studio install, but they do allow you to express pre and post conditions and object invariants.

Different options are available for enforcing the contracts as compile-time or run-time checks (or both).


Take a look at CuttingEdge.Conditions. It allows you to write your preconditions in a fluent manner, as follows:

ICollection GetData(int? id, string xml, IEnumerable<int> col)
{
    Condition.Requires(id, "id")
        .IsNotNull()
        .IsInRange(1, 999)
        .IsNotEqualTo(128);

    Condition.Requires(xml, "xml")
        .StartsWith("<data>")
        .EndsWith("</data>")
        .Evaluate(xml.Contains("abc") || xml.Contains("cba"));

    Condition.Requires(col, "col")
        .IsNotNull()
        .IsNotEmpty()
        .Evaluate(c => c.Contains(id.Value) || c.Contains(0));
}

You need C# 3.0 or VB.NET 9.0 with .NET 2.0 or up for CuttingEdge.Conditions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜