Wednesday, June 29, 2005

.Net Diagnostic Class

I was just reading about this great class designed to aid program debugging. The idea is that you insert these as you code, and then they significantly cut debugging time, but the great thing is that this code is only compiled into the Assembly (the EXE) when you are in debug mode. Once you compile to release the compiler strips all this code out. So that makes this great for seeing what your code is doing and running extra validation to catch bugs before they happen, but without adding any overhead to your final code.

Imports System.Diagnostics

Debug.WriteLine
This will help you keep track of what your code is doing at the time of an error by displaying a custom message on the Immediate window (from the menu strip at the top Debug > Window > Immediate). So for example before you access a file you could write:

debug.writeline("Starting data access")

Or before you run a validation algorithm:

debug.writeline("Starting validation")

Debug.Assert
This one is great because it allows you to do validation purely while debugging. So say a passed variable should contain something, then you could use:

Debug.Assert(passedVal <> "") 'passedVal is not equal to nothing

The program will only get past this point if this line of code between the brackets is true. And you can also add helpful text that will appear on an error screen when the result from the code is false. So say you where going to do some integer maths from a function that deals with floating point calculations.

Debug.Assert(passedVal >= 0, "Number is less than 0 and so can't be used in integer maths")

When a Debug.Assert is triggered because the code inside it isn't True then an error window is displayed with the error message (if you have typed one that is) and pressing Retry will highlight the Debug.Assert that caused the error so you can fix your code.