The other day I was sitting in the office, when the door opened and J.F. came in with a lab partner. Seeing me, he said that I was just the person who could help them.
J.F. tells me that he not infrequently finds himself sitting in class and noticing the professor making some kind of mistake on the blackboard. He says when this happens he imagines that I might walk in at that moment and fix things, because I don't make mistakes like that. He gives me a doodle he's done showing such a scenario:
J.F. and his partner were doing some sort of project for their aerospace class, and it involved finding the velocity necessary to send a spaceship from Earth-orbit to Jupiter-orbit in a given transit time.
The way you do this—assuming you're not doing a multi-stage or chaotic orbit—is to assume a particular orbit (circular, parabolic, elliptical, hyperbolic), and then solve its transit time equation for velcoity. You then minimize velocity for the particular time, shifting between orbits as necessary.
The code they brought to me contained nested while loops contained within and containing multiple if clauses. It was a mess.
And that's a problem for me, because I believe—strongly—that code should be beautiful.
Some people say that beauty is a kind of “bounty quality” which cannot be sought directly, but only realised through the pursuit of intermediate goals. This may be true, it is also possible that aesthetics can be judged at sufficient intermediate points that the separation of beauty and functionality becomes negligibly small.
That is, mere functionality is not a quantifier of successful code-writing. I believe analogous laws to hold for many things in life, but I've repeatedly had to drill this idea into unwilling students in my four semesters of teaching computer science. As I see it, programs are the earthly incarnations of more abstract concepts which exist in an idealized form in a kind a of “Plato's Heaven”. It is the job of the programmer to understand these forms and give them substance.
Thus, messy code is often a sign that the programmer does not grok the problem and its solution in an abstract sense. One of the first things I do to fix this is to facilitate the removal of all the unnecessary crud in the code. Next, I show how the logical structure can be simplified and how functions can be abstracted. At this point, if the problem has not already gone away, there is usually a closer correlary between the implementation and the form it represents, making it easy to identify critical differences between the realized and desired forms. I am clarifying what has been done so it is easier to see what must be done.
Indeed, when I'm done working with J.F. the code bears scant resemblance to what he came in with but works perfectly. He looks at it and shakes his head in wonder, “I saw what you did, but I don't know how you knew to do it.”