by Mathias
18. September 2009 06:12
I found a bug in my code the other day. It happens to everybody - apparently I am not the only one to write bugs – but the bug itself surprised me. In my experience, once you know a piece of code is buggy, it’s usually not too difficult to figure out what the origin of the problem might be (fixing it might). This bug surprised me, because I knew exactly the 10 lines of code where it was taking place, and yet I had no idea what was going on – I just couldn’t see the bug, even though it was floating in plain sight (hint: the pun is intended).
Here is the context. The code reads a double and converts it into a year and a quarter, based on the following convention: the input is of the form yyyy.q, for instance, 2010.2 represents the second quarter of 2010. Anything after the 2nd decimal is ignored, 2010.0 is “rounded up” to 1st quarter, and 2010.5 and above rounded down to 4th quarter.
Here is my original code:
public class DateConverter
{
public static int ExtractYear(double dateAsDouble)
{
int year = (int)dateAsDouble;
return year;
}
public static int ExtractQuarter(double dateAsDouble)
{
int year = ExtractYear(dateAsDouble);
int quarter = (int)(10 * (Math.Round(dateAsDouble, 1) - (double)year));
if (quarter < 1)
{
quarter = 1;
}
if (quarter > 4)
{
quarter = 4;
}
return quarter;
}
}
Can you spot the bug?
More...
c3df0143-03ee-458e-a97a-681665595c98|0|.0