There are several signs of bad code. Frances Buontempo considers ugliness, stench and discord in a search for beauty.
First I must apologise. I have failed to write an automatic editorial generator. I was distracted by @TicBot on twitter and after many delightful chats about biscuits, it is clear I should write an @OverloadBot and leave them to figure it out between themselves. I will try harder for the next edition. Meanwhile, I will step back and consider what makes something delightful or indeed beautiful for motivation. Let us start by considering its contrapositive. What makes something repulsive or ugly?
People frequently refer to code smells, indicating that the code in front of their eyes falls somewhere between inducing a nervous tick or the desire to run away screaming and inducing a sense of general, or specific, wrongness. Referring to a smell produced by looking at something is decidedly odd, though possibly traditional. Martin Fowler claims the phrase was first coined by Kent Beck. Furthermore he says, “ A smell is by definition something that’s quick to spot ” [ Fowler ]. Perhaps you can spot things with your nose as well as your eyes, though our eyes will show us the usual suspect smells including code duplication, long functions and many similar subclasses. There are other types of code smells that we neither sniff nor see, for example boredom: “ Boredom is a smell that you understand the problem well enough to automate a solution ” [ c2 ].
It is possible to extend the heuristic of bad smells for code analysis to other senses. This brings to mind some mention of a program called CAITLIN, ‘musical program auralisation’ system for Pascal programs, mapping program data to sound. [ Vickers02 ] Many years ago in an attempt to speed up a program running on an embedded device, a colleague and I inserted beep statements in a loop to see how often a function was called. This was a resounding success, though we were banished to the kitchen since the rest of the team found it deeply annoying. I suspect CAITLIN goes further than simply beeping. It draws on previous research that could be used to represent C programs, and automatically maps loops and structures to sound motifs or short tunes. The authors notice that a musical background made no difference to the results. Regardless of musical expertise the sound motifs seemed to help students detect bugs more quickly. Music would appear to have deep roots in the psyche. Dara Ó Briain’s latest Science Club program on BBC2 explored the science behind music, noting that music, specifically the beat, could have a profound impact on people suffering from Parkinson’s disease [ Science Club ]. The rhythm helped them walk more stably, possibly by allowing a different path through the brain to be formed, short circuiting the broken parts. Music seems to form some kind of universal language and can immediately cause visible delight in young children. Analysing source code aurally therefore seems like a very good idea.
We have considered smells and discord to detect bad and ugly code. We have also noticed that our eyes can tell us much about a code base. Furthermore, there are many code metrics, which will summarise the code space numerically, ranging from test coverage to complexity and beyond. An obvious next step is to graph these, to provide a neat summary. A quick google found NDepend’s Metric View [ NDepend ], which appears to represent a code base as coloured rectangles. I would need to try this on a code base or two to get a feel for what what counts as good or bad, from this visual perspective.
What makes code good? Certainly it should be fit for purpose, and not noticeably contain bugs. This doesn’t go far enough though. It is possible to automatically generate code to perform tasks, but the generated code is frequently ugly. Of course, we do not yet have a clear definition of ugly though mentions of stinks and discord provide a vague idea. The time has come to flip back our contrapositive and reconsider what is beautiful or delightful. Recall the title of Knuth’s classic algorithms books, the art of computer programming. Why does Knuth insist on using the word art, considering so many of us frequently try to suggest we are computer scientists or engineers? “ We have seen that computer programming is an art, because it applies accumulated knowledge to the world, because it requires skill and ingenuity, and especially because it produces objects of beauty ” [ Knuth74 ]. What on earth does it mean to claim a computer program is beautiful? An acquaintance of mine is currently trying to learn python and cannot see why I insist on suggesting different ways of doing something. If it works, it works. Full stop, end of. No discussion necessary. Which makes trying to discuss why I feel this matters somewhat challenging. As a person with a background in pure mathematics I have been trained to appreciate beauty. It is possible to write a long, laborious and difficult to follow proof in analysis. Point proved, QED, full stop, end of. However, it is often possible to prove the same thing formulated in topological terms. Clearly, this is total waste of time if you’re just trying to prove a point. Nonetheless, the topological version will frequently be two or three lines long. The compactness is made possible partly by the level of abstraction introduced. There is a fine balance between terseness and elegance, and beauty sits firmly with elegance and simplicity. Controversially, I would like to suggest spotting beauty is learnt. People use phrase like a ‘trained eye’ or ‘trained ear’. Perhaps experienced programmers develop a trained nose, to spot code smells. Algebra is beautiful, but most school children cry dismay when they first meet the subject, complaining that mathematics should be about numbers rather than letters. The delight and joy that comes from appreciating algebra is not innate; it tends to come from a long hard slog and good mentors. So, to re-ask the question, Victor Norman asks “ But, what difference does it make that the code is ugly? If the code works correctly, who should care that it is ‘ugly’? ” [ Norman ]. As with my python learning friend complaining that if it just works that’s good enough, how can we answer this point? Returning to musical program auralisation, most children will engage with simple music, perhaps in the form of nursery rhymes and will take a long time to appreciate other more complicated musical motifs. Depressingly, many will stick with the simple obvious forms and never progress on from the inane to the beautiful. Does this matter? Almost certainly not, however, they are missing much joy and delight, in the same way that people who never get the hang of algebra are missing out.
Why does beauty matter? Perhaps it doesn’t really, though if something is clear, elegant and simple it might be easier to work with. Let us return Knuth again.
Alas, people these days rarely measure a computer scientist by standards of beauty and interest; they measure us by dollars or by applications rather than by contributions to knowledge, even though contributions to knowledge are the necessary ingredient to make previously unthinkable applications possible. [ Knuth interview ]
Perhaps we could argue beautiful code is easier to test and refactor and then measure this in dollars. More abstractly, Norman [op cit] suggests that art and computer programs are both about communication. We delved into communication in Overload 112 , though from the viewpoint of developing software as communications rather than in a search for beauty. An expert musician or artist will notice patterns and structures that a novice may miss thereby failing to appreciate some of the elements of cleverness or joy in the composition. Similarly the structure of a program may follow a design pattern, which a newbie may not spot. Beauty goes beyond communication though. Introducing a level of abstraction, through algebra, repeating sound motifs or developing new data structures and algorithms can open up new possibilities. Recall the surprise at the discovery of the possibilities of template metaprogramming? Being able to read, write and think in a specialist area, be it music, mathematics, code or even a human language is the goal of a skilled artisan. “ Fluency goes beyond reading and writing. A fluent speaker of a language begins to be able to think in idiom ” [ Armitage ]. Armitage goes on to say of writing code:
A great deal of it is much more like sculpture. Data, technology, code, as a slab of clay, to be manipulated, explored, felt between your fingers, and slowly turned into something substantive. It’s practically the opposite of engineering. It’s an artistic discipline: beginning with sketching and exploring, and then building on those sketches slowly through iteration, watching a final structure emerge.
Perhaps we should avoid the age-old debate about whether what we do is engineering or not, but rather observe that taking pride in creating something beautiful should be possible whichever side of the debate you come down on. He then suggests that computers allow us to think new thoughts. On the face of it, this is a remarkable claim. However, frequently introducing new representations for ideas, in effect new languages and levels of indirection, allows new ideas and new ways of solving problems to emerge. Introduction of the calculus gave ways of expressing both old and new problems in a different way. Would we have ‘e’ without Newton or Leibniz?
Code can be good, bad or ugly. Indeed, correct code, fulfilling user requirements can be good, bad or ugly. Trying to define ‘good’ code is difficult, but bad and ugly code is easy to spot. It smells. It makes a discordant racket. It possibly burns your skin or tastes like wallpaper paste, though we haven’t yet seen a way of mapping it to touch or taste. Certainly, it looks ugly. It could be long and lumbering functions, with slightly more boolean flags wedged in than you would expect, or using two such flags to describe three possible states and so on. It is easy to list bad and ugly traits shared by bad and ugly code. Instead, let us end by considering good traits shared by beautiful code. I suggest it should be as simple as possible, but no simpler. If it leaves you excited and wanting to play with an idea further it might be a masterpiece. Trying to form a definitive list of what makes something beautiful or even good may be an impossible task, so I’ll leave each reader to consider what they find beautiful.
Some programs are elegant, some are exquisite, some are sparkling. My claim is that it is possible to write grand programs, noble programs, truly magnificent ones![ Knuth74 ]
[Knuth74] ‘Computer Programming as an Art.’ Communications of the ACM 1974 pp 667–673 http://delivery.acm.org/10.1145/370000/361612/a1974-knuth.pdf?ip=22.214.171.124&id=361612&acc=OPEN&key=4D4702B0C3E38B35%2E4D4702B0C3E38B35%2E4D4702B0C3E38B35%2E6D218144511F3437&CFID=301037474&CFTOKEN=96163289&__acm__=1394471960_bd6a846ec3f24b8c06634deea10cfab4
[Vickers02] Vikers & Alty ‘When bugs sing’ Paul Vickers, James L. Alty 2002 http://hdl.handle.net/2134/3357