Assertion Points

I love using assertion points such as the following:

Debug.Assert(HasBrainGameManager, "This instance has no brain games game manager");

I started using assertion points after realizing how powerful they are (System.Diagnostics.Debug). After about a year of doing so, I started reading MSCode Complete and they have a whole chapter about assertion points.

 

 

Adopting assertions especially for debug mode of an application is one of the best things I know a programmer can do:

1. Always know when your code is broken.

2. Find out how strong are assumptions that you made while writing your code.

3. The assertion points are like tests and they are tests that run whenever your code is executed

4. If you use assertions enough you will also know that your code broke right away with little to none stack tracing.

5. In multi threaded applications the debugger stops inside the correct thread

6. Debug services – this is a very important part of assertion points in general and specifically for .NET applications

Examples for assertions:

1. Check method input parameters

2. In the beginning of a catch clause – right before you do anything about it

3. Check assumptions that you make like existing files or directories

4. Unexpected code – in some cases there is code that should not be executed and we can check this by putting an assertion in the restricted area

5. Conditional debugging helpers

There are a few things to watch when using assertions:

1. Make sure that the code that runs in debug mode will execute without any side effects. By this I mean that you should not call code that changes the internals of the software (Properties, Methods and others).

a. Bad example code that runs in release mode only:

i. Debug.Assert(HasBrainGameManager, "This instance has no brain games game manager");

ii. Debug.Assert(HasBrainGameManager(), "This instance has no brain games game manager");

b. Good example:

//assign a bool - this code runs in debug and release modes

bool hasWrriter = HasWriter;

//use it - this code runs in debug mode only

Debug.Assert(hasWrriter, "The logger has no writer");

 

I have a lot more to say but little time…