Thursday, October 20, 2011

Instrumenting code using #if DEBUG #endif Block


Its usually very difficult to debug  a software with large amount of code. People generally writelogs, write traces while debugging code and often forget to remove these .this will result in undesirable messages in production code.
A bad way of instrumenting  code is shown below
static void calleeFunc()
        {

            try
            {

                Trace.WriteLine("in callee func");
                Console.WriteLine("in callee func");

                int i = 1;
                int j = 0;
                int k = i / j;

            }
            catch (Exception ex)
            {

                throw ;
            }


The problem with  this snippet is that it displays unnecessary messages when compiled in Release mode.This can also lead to security vulnerabilities
A way to solve the problem is the use of conditional compilation directives provided by c# compiler.
The  #if DEBUG end if block  enables the trace message and console messages in debug mode and strips it of in release mode

   static void calleeFunc()
        {

            try
            {
#if DEBUG

                Trace.WriteLine("in callee func");
                Console.WriteLine("in callee func");
#endif
                int i = 1;
                int j = 0;
                int k = i / j;

            }
            catch (Exception ex)
            {

                throw ;
            }

        }
The use of the #if debug  #endif block helps eliminate unnecessary debug messages in production(Release Mode code) This way you can stop spending large amount of time in removing code used for understanding or tracing.





No comments: