Software Development (CSC 321 2016S) : EBoards

CSC321.01 2016S, Class 13: Test-Driven Development


Overview

Preliminaries

Admin

Upcoming Work

Good Things to Do

Academic

Peer

Questions

Refresher: Incorrect code

class TimeSetter
  def self.convert(d)
    y = 1980
    while (d > 365) do
      if ((y % 400 == 0) || (y % 4 == 0) && (y % 100 != 0))
        if (d > 366)
          d -= 366
          y += 1
        end
      else
        d -= 365
        y += 1
      end
    end
    return (y,d)
  end
end

What does this code try to do?

How would you check whether the code is correct, assuming it compiles?

Suppose we are running unit tests, what tests would you run?

(Optional) What's wrong with this code?

Loop invariants

Code smells

What about that code might have raised concerns, even before the tests never completed?

Fixing the Code

First attempt

class TimeSetter
  def self.convert(day_in_year)
    year = 1980
    # Keep moving into the next year until we are down
    # to a reasonable number of days
    while (day_in_year > 365) do
      day_in_year -= 365
      # There's an extra day in a leap year!
      if (isleapyear year)
        day_in_year -= 1
      end
      year += 1
    end
    return (year,day_in_year)
  end

  def self.isleapyear(year)
    return (year % 400 == 0) || (year % 4 == 0) && (year % 100 != 0);
  end
end