Saturday, May 14, 2011

How to write programs

I have spent much of this week proofreading the programming assignments for my Fall course on introduction to programming. The texts contain many recommendations about what to put in but no recommendation on what not to put in, and they themselves are often rather wordy. I trimmed the texts, starting by removing 90% of the introductory paragraphs that give the broad context. When a student reads an assignment, his primary worry is to see what he has to do, not how the problem fits into some area of broader interest, so a sentence or two is sufficient.

In one lecture, I give a "design recipe" to design programs:
1. Define the data and provide concrete examples.
2. Define the procedure’s type signature and call structure.
3. Write a contract for the procedure and provide some test cases.
4. Write the procedure (in code).
5. Run your program on your test cases.

This year I think I'm going to add a step.
6. Clean-up your program - remove extraneous lines, consider removing helper procedures that are only called once, consider replacing nested "if" conditions by a list of cases, shorten or lengthen variable names, etc.

Or perhaps I could simply suggest:
6. Delete everything and do steps 1-5 over.
Isn't that what many good writers do? I am sure that regardless of the care with which the programmer has designed it, a program would be much better and much more elegant the second time.


  1. In either case, what is the goal with point 6? To make the code easier to read? Easier to reuse? To double-check for bugs? That might help decide your answers.

    I personally would not encourage removal of helpers when they can make the code more transparent nor would I always suggest re-starting from scratch...

    ... if you are writing a masterpiece (in code, paint, or a novel) I could see that first writing a sketch and then re-starting is natural. But for a programming assignment I am not sure what justifies the extra work. On the other hand double-checking for bugs and making the code more readable is good both for students and graders!

    What are these very verbose books?

  2. I am not really serious about "deleting everything". As you said, for a programming assignment, it's not worth it (unless you've twisted yourself into such a knot that starting from scratch would be easier than completing the partially written code.)

    The goal is to make the program easier to grade.

    I advocate to "consider" removing helper procedures, not systematically to remove them. People err both ways in that respect: some use too few, some too many.


Note: Only a member of this blog may post a comment.