开发者

How do you assert in algorithimic code in .NET?

开发者 https://www.devze.com 2023-01-26 01:44 出处:网络
I am currently developing a small AI framework ( genetic algorithms / neural networks) in C#, for a university project.

I am currently developing a small AI framework ( genetic algorithms / neural networks) in C#, for a university project.

My first concern is developing a reusable framework, so I am designing everything to be pretty modular. I know I am paying off a price for this (performance), but I feel that I have more to gain than to lose with it (preferable to have code twice as slow than have to lose twice as much time later trying to find impossible to find bugs and losing lots of time trying to add new things that are hard to introduce in a monolithic block of code).

I would like to have lots of checks on different parts of my code, assertions, basically. Check if when running method X I am indeed in a correct state, etc. Those kind of assertions are useful when developing, but I'd like them to stay away from release code (that is, when I decide that I'll want to leave this working for the night to get my final research results).

I can see several ways of accomplishing this:

  1. System.Diagonists.Assert family of methods.
  2. Code Contracts
  3. Having if (x) then throw InvalidStateException() surrounded by #if DEBUG / #endif

How would you do it and why?

I am also aware of Unit-Tests (I am using them), but I'd also 开发者_C百科like to have some kind of assertions on the code, too.


You could use a static method like this:

[Conditional("DEBUG")]
public static void Assert(bool condition, string message)
{
    if (!condition)
        throw new InvalidStateException("Assertion failed: " + message);
}

And assert like so, assuming the method is defined in a class called Util:

Util.Assert(a == b, "a == b");

Calls to this method will only be emitted by the compiler when the DEBUG symbol is set, thanks to the ConditionalAttribute. So you don't need to wrap such calls in any #if directives. This will lead to less code clutter.

(Note that the method itself will still be compiled. This allows you to use such methods in different assemblies!)


The advantage of #if/#endif is that not only is the call to the assert function eliminated, but also all the work preparing its parameters (which hopefully don't have side effects...).

0

精彩评论

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