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.
An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. You can write a message to be written if the code returns False, check the example below.
The assert() function tests the condition parameter. If it is false, it prints a message to standard error, using the string parameter to describe the failed condition. It then sets the variable _assert_exit to one and executes the exit statement. The exit statement jumps to the END rule.
Assertions in C/C++ Following is the syntax for assertion. void assert( int expression ); If the expression evaluates to 0 (false), then the expression, sourcecode filename, and line number are sent to the standard error, and then abort() function is called.
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With