Barbara Ericson, Allen B. Downey, Jason L. Wright (Editor)
Section9.9Incremental development versus planning
In this chapter I have demonstrated an approach to program development I refer to as rapid prototyping with iterative improvement. In each case, I wrote a rough draft (or prototype) that performed the basic calculation, and then tested it on a few cases, correcting flaws as I found them.
Although this approach can be effective, it can lead to code that is unnecessarily complicated—since it deals with many special cases—and unreliable—since it is hard to know if you have found all the errors.
An alternative is high-level planning, in which a little insight into the problem can make the programming much easier. In this case the insight is that a Time is really a three-digit number in base 60! The second is the “ones column,” the minute is the “60’s column”, and the hour is the “3600’s column.”
Thus an alternate approach to the whole problem is to convert Times into doubles and take advantage of the fact that the computer already knows how to do arithmetic with doubles. Here is a function that converts a Time into a double:
You might have to think a bit to convince yourself that the technique I am using to convert from one base to another is correct. Assuming you are convinced, we can use these functions to rewrite addTime:
This is much shorter than the original version, and it is much easier to demonstrate that it is correct (assuming, as usual, that the functions it calls are correct). As an exercise, rewrite increment the same way.
Listing9.9.2.Write your implementation of increment in the commented area of the active code below. If you get stuck, you can reveal the extra problem at the end for help.
Let’s write the code for the updated version of the increment function. increment adds a number of seconds to a Time object and updates the values of the object. This version should use convertToSeconds and makeTime.