Wednesday, December 15, 2010

How not to write code

Grading for my freshman programming course, I saw this and similar horrors:

if condition then true else false

instead of


My TAs did not think that should be penalized, "because it's not a big deal". Indeed, I have taught that code ought to be (1) correct, (2) readable, and (3) efficient. The piece of code above is correct; having seen much more mysterious constructions, I cannot argue that it's not readable; and the loss of efficiency is negligible. But it's not elegant! That is just one example of bad style among many. I forgot to stress one important aspect in class: code should always be (4) beautiful!

Perhaps we should have some "beauty points" in our grading scale, and I should have some exercises of the form: take this ugly piece of code, and make it beautiful. Students would complain about possible discrepancies between different TAs' esthetics, of course, but I suspect that there is a hidden yet broad consensus to recognize beauty in code: we know it when we see it... the challenge is to define it!

Similarly, in math, particularly in courses on how to write proofs, perhaps there should be some exercises of the form: "take this ugly proof and make it beautiful".


  1. I disagree. You get a student to start programming, and that's a great thing. You start to inflict various additional desiderata too soon, and you risk putting them off. If it works, it works.

  2. I think this goes for textbook writers as well, beautiful (pseudo)code inspires you to implement it.

  3. I have to disagree with you too, but in a different way Paul does. I think a person that write code in the sense you are presenting it, is not just writing an ugly code, but in certain way he/she does not understand the logic associated to it, and that is caused for a failure with some other basics skills a programmer should have even while giving the first steps.

  4. I disagree as well. But the TAs should certainly point out the simplification.

    Maybe you should start giving courses to many current researchers on how to write non-ugly proofs. As a young researcher trying hard to write nice papers, I don't find many role models.


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