Monday, December 27, 2010

Quickly Testing and Changing Code

Sometimes when running software it is hard to make a particular code path execute.  Like if you want to ensure your code behaves correctly when bad data is passed to your function.  I love Visual Studio and the debugging capabilities are one of the things I love about it.  Using the watch window the values of variables can be changed to check those code paths, and by right clicking on a line one can set the next statement of execution wherever they want.

If we have code like this

int customerId = getCustomer("bob");
bool log = Settings.ShouldLog();
if(customerId < 0 && log)
    log.LogError("bob is invalid");

We can make the log code run by setting a breakpoint on the if line and then changing customerId to -1 and log to true in the watch window.  If we want to change the code in the if block and retest changing these values every time is repetitive.  Changing the breakpoint on the "if" to a conditional breakpoint allows additional code to execute when the breakpoint is evaluated.  We can leverage this feature to change the breakpoint condition to "customerId = -1."  Each time the breakpoint is evaluated customerId will be set to -1.  This is great, but in our example we have two variables which need to be set properly to satisfy the if condition.  To change both variables the conditional breakpoint can be changed to a lambda like this: () => { customerId == -1; log == false;};

I've found this technique can help me rapidly iterate on code changes to ensure edge case scenarios or hard to reproduce data scenarios execute properly for code that isn't under test.


Sean said...

I think you need some double-equals in those conditions. But, yes, it's pretty awesome.

Dave said...

Thanks for the catch Sean! That is what I get for writing code in Blogger instead of VS =)