Last week I wrote a program. I wrote about it on this blog (Making Magic With Software) but only about what was visible to the user. This week I decided to show some of the code behind to my students as part of asking them to write a similar program. As often happens this did not turn out quite like I planned. Basically it turned into “let’s make this program better.” I could pretend that this was on purpose but let’s be honest – it wasn’t.
Having written code for something like 40 years I confess I get a bit cocky about it sometimes. I think I can start writing code without planning it out or even thinking out the whole plan. This usually results in something that works but is not quite what it should be. What did I do wrong this time? A bunch of things.
The most obvious was that I took an application that would be easier to code using a two dimensional array and did it with a one dimensional array. Why? Less typing. Poor reasoning I know. Now doing this was fairly easy for me (I’ve done similar many many times though usually with a better reason) but it was not going to be easy to explain to students. That’s a sure sign that a better design is needed by the way. So I showed the students how to set things up as a two-dimensional array.
The other thing I did wrong was to have “magic numbers.” That is to say that some values were hard coded and used several times. Why? I knew how many objects I needed and it was never going to change. Famous last words. Showing this to students I realized that the code would be more easy to understand and more reusable if I defined and used constants rather than hard coded numbers. properly named values actually make the program easier to understand. What does “8” mean? Clearly not as obvious as “row.”
So I fixed the program in front of the students and explained the why of each change. Hopefully it made an impression. Even if it didn’t at least they have a better written sample piece of code to read and learn from. And I reminded myself to take “throwaway code” more seriously. You never know when it is going to pop up again.