Pair-programming with another one of my wonderful team colleagues last week, we came across a tricky little bug caused by a (correctly behaving) feature of Java Calendar.
We tried to replicate the bug (to do with matching something within a date range) by running the application as described in the bug report. The application worked just fine.
We eventually tracked down the problem - setting the system time to the afternoon we replicated the bug. If we'd started on this bug after lunch, instead of first thing, we'd have found it straight away. I'm sure there's a moral there somewhere!
The HOUR of a Calendar is based on a 12 hour clock - we found some code that was setting the HOUR (to 0) when it should have been setting the HOUR_OF_DAY. The effect of setting the HOUR to 0 is that before 12pm, the hour part of the date is set to 0, and after 12pm the hour is set to 12 - this lead to the bug we had to fix.
OK - so it's not very interesting - but hopefully at least if you managed to stay awake during the whole of this article you'll remember it next time you come across something using Calendar.HOUR and the alarm bells will ring.
We were lucky that someone spotted this bug - it could have easily been missed. How do you find something like this where the bug only appears in the afternoon?
Also - it feels to me like the feature of being able to set the HOUR rather than the HOUR_OF_DAY is a bit superfluous and almost invites bugs like the one we fixed. How much time is saved by the existence of this feature compared to the time wasted by it? What does the time wasted by this feature tell us about how to write APIs? The experience has reminded me of a talk at a company conference run by one of my previous employers; "Features - just say no!".
Posted by ivan at August 8, 2005 7:45 PMThe solution is not to use current time of day in tests, but to pass in the time. Then you can pass in a variety of times and make sure that they all work. For production, the caller passes in the current time.
Posted by: Curt Sampson at August 9, 2005 2:44 AMThat's exactly what we did when we wrote the tests to fix the problem. (Neither of us wrote the original code or it's lack of tests). (And to be fair, I did write "How do you find something like this" not "How do you test for something like this" - once found it's easy to test).
Ivan.
Posted by: ivan at August 9, 2005 8:05 AMOOPS - sorry - there was a good comment about cruise control but it's got deleted in a flurry of automated spam comment deletion. Whoever it was who wrote it - very sorry, please re-post if you can forgive me!
Posted by: ivan at August 17, 2005 9:05 AM