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:
How would you do it and why?
I am also aware of Unit-Tests (I am using them), but I'd also 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!)