Spike solutions and refactoring - a Python example
Archive - Originally posted on "The Horse's Mouth" - 2012-06-13 18:09:51 - Graham Ellis
Refactoring - taking a program that works (as far as it goes) and restructuring it so that it can go much further - that its code can be reusable, that it's more robust, that it can be updated to do more, and so on.
Spike Solution - an answer to a problem that can go no further, and perhaps ignores lots of special cases, typically written as a proof of concept or as a training exercise.
We write a lot of spike solutions during our courses - demonstrations that will go no further, programs that rely on the user's inputs being sensible because they're not validated, code which isn't easily reused because of its very specific nature with values hard-coded into it. And we right those because data validation and code structuring take time, and if we're teaching (say) Python's lists and tuples, we don't want to dilute the teaching and extend the course to the extent that the delegates can't see the wood for the trees.
One of the exercises on our Python course asks the user to take the following tuple: mlen = (31,28,31,30,31,30,31,31,30,31,30,31)
and produce two lists with 365 elements each. The first list is to contain the number 1 31 times, then the number 2 28 times, and so on - so that a user of the list can look up a day number of the year and (in a single reference to the list) know what month that day is in. A second list is also produced, containing 1 through 31, then 1 through 28, then 1 through 31, and so on - thus giving the ability to look up any day number of the year and tell you which day number it is within a month.
The first sample answer - spike solution is [here]. It's about half a dozen lines of code, and those code.
Refactoring, we may wish to make full use of those lists within other code, and we'll also wish to be able to handle special cases like leap years. Better, then, to write the code as a series of functions and add a test harness. And add sample output too. Much longer code - see [here]. And can't be done until we've covered functions later in the course.
We do emphasise good structure, good commenting and good documentation throughout our courses. But we also emphasise practical programming and exercises, and at time there's a very great deal to be gained by using a spike solution to learn, to test algorithms, and to experiment.