Abstract: Driving out a correct implementation of week numbers using TDD

The implementation of weeks according to ISO 8601 (used e.g. in Sweden) is faulty in .NET Framework. In particular the GregorianCalendar and CultureInfo classes are faulty when it comes to ISO 8601.

So, how do we know that the implementation of ISO 8601 is faulty using TDD? We come up with a test that fails. By the ISO definition the first week is the week with the year's first Thursday in it. So, we know that e.g. 2003-12-31 is actually week number 01 of 2004 since it is a Wednesday and thus belongs to the first week. The following is a first attempt at a test:

   1: [Test]
   2: public void GetWeekOfYear_20031231_Week01()
   3: {
   4:     GregorianCalendar calendar = new GregorianCalendar();
   5:     DateTime date = new DateTime(2003, 12, 31, calendar);
   6:     int week = calendar.GetWeekOfYear(date,
   7:             CalendarWeekRule.FirstFourDayWeek,
   8:             DayOfWeek.Monday);
  10:     Assert.AreEqual(1, week,
  11:         "The week was not the expected for ISO 8601!"),
  12: }

Now we get a red bar and we know that the implementation is flawed. However, this is only a single test. If we get a green bar, is the implementation correct? No, of cource not. We need to write more tests to be sure.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.