CodeSOD: Stop, Watch

On one hand, we should all be doing our revision tracking in our source control system, and we shouldn't let code comments tell the story of why or how the code changed. On the other, when it leaves us the history of WTFs in the current version of the code, it's actually delightful.

Take this anonymous submission, which includes the whole story of the code, all at once.

if (sw ==null) { sw = new Stopwatch(); ResetStopwatch(); } // Was the following: the purpose was: check if there is a stopwatch, if not, do the create one and reset it. // the code above seems simpeler //try //{ // bool check = sw.IsRunning; //} //catch //{ // sw = new Stopwatch(); // ResetStopwatch(); //}

The original version, commented out, uses a null reference exception for control flow. If sw.IsRunning throws an exception (because sw is null), we catch it and create a new stopwatch.

Which is certainly more complicated and annoying than a simple null check. And the fix was "simpel". And we have the whole narrative of the original, why it changed, and what it is now.

[Advertisement] ProGet’s got you covered with security and access controls on your NuGet feeds. Learn more.

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.