How to write beautiful code

Beautiful code is elegant and simple – it is concise but clear. There is a balance in the code – a rhythm in the definition and structure of conditionals and the loops. The intent of the each function shines through the code – a pattern in the creation and interaction of the classes and methods in classes that combines the code into a coherent and beautiful unit. Beautiful code is concise, there are no wasted variables or endless conditionals – it is a pleasure to read not just because of the ease of reading but from the way in which it communicates the ideas and intent of the
programmer.

Well, now that I have waxed lyrical about what is good code, the next logical step would be to figure out how to write such code. Beautiful code starts with good understanding – in order to write beautiful code the first step is to understand the problem you are trying to solve. The next step is to have a clear idea of the solution and the approach you are going to take. These two things itself are entire subjects in software development – so I shall for the purposes of this post, assume that you have a clear idea of the problem you are solving and the approach you are going to take to solve the problem :-)

Even with these conditions met (understanding the problem and identifying the solution), sitting down in front of a blank page and writing out the excellent bug free code is almost impossible IMHO. The best programs that are out there are the result of an iterative process of coding and re-coding repeatedly – almost obsessively. Writing a program is like building a clay sculpture – you start of with a lump of clay, then you broadly shape it and  then keep removing and adding bits and pieces till you get your sculpture – sometimes you have to remove a big piece and add another instead and sometimes you simply throw everything  away and start over.

Writing beautiful code is hard – a seemingly simple algorithm like the Quick sort is the result of years of effort to come up with a concise and elegant implementation (in fact Quick sort has several implementations).  Even a simple piece of code like the quintessential “Hello World” program can be written in so many ways(in fact it is maintained as a separate GNU project).

So when do you stop iterating ?  There are some factors to consider in making this decision – usually if you are working on commercial software
this decision is not in the developers hands. The almighty deadline determines the ‘done-ness’ of your code – indeed, this seems to be
psychological impetus for a lot us. I have seen a lot of places and projects where people find it hard to work without a deadline looming,
like a Damocles sword, above their heads. Indeed I suspect there is something psychologically appealing to having this decision taken out of
our hands.

Again, for the purposes of this blog post, let us assume you have control over when you decide your code is done and you decide to release it only after you feel it is good enough. The question then becomes how do you know that what you have is beautiful code?

The first requirement of good code is, that it should work. If your code does not solve the problem it was intended to solve – you need to go back to the drawing board my friend – this is a necessary pre-requisite but it is not a sufficient condition for beautiful code.

One way to identify beautiful code is to read about programming – programming  methods, philosophies, etc.  I have book list of good software books to read you can start with (you can look at my post on internet reading for more book lists and articles).   In order to be a good sculptor, you need to know what beautiful sculpture look like – so you look at pictures of great sculptures – in fact this is usually a part of the curriculum for art programs. Similarly, sculptors look at examples of bad sculpture in an effort to recognize what to avoid.  So, in order to identify beautiful code look at examples of beautiful code – code written by great programmers and code written for great projects as well as bad code, ugly code.

Unlike sculpture – where you would have to travel to Italy to get a look at David or The Pieta – you have a lot of good code to read available at your fingertips – just open up the internet and look around :-) There are plenty of open source projects that share their code-base  – start with GNU, Sourceforge, and Google code (check out this post on the worlds oldest software repositories). If that’s not enough take a look at the examples in the ‘Code Complete‘ book (Other books you can look at ‘Beautiful Code‘, ‘Beautiful Data‘, ‘Clean Code‘ and ‘Coders at Work‘). Identify the patterns followed in beautiful code and the patterns you see in ugly code.

Another very important thing to recognize  is when you have stopped coding to a requirement. Good code is spare -it provides a solution to the problem at hand – no more – no less. A sign of good code is when you go through it and feel there is nothing you can remove from it – to paraphrase one of my favorite quotes by  Antoine St Exupery)  – “A programmer knows he has achieved perfection not when there is nothing left to add, but when there is nothing left to take away.”

And finally, the only way to make beautiful code is to write lots of code and publish it. All programs have constraints – some are technical and others logistical and yet others philosophical – good code is a elegant balance between these constraints.

So budding programmer –  Good Luck and Happy Coding !! I leave you with the following philosophy from the Python programing community –

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

PS: I refer to coding and programing interchangeably in this post. What I mean by these terms is the act of writing a software program.

PPS: You can get the “Zen of Python” poem by typing “import this” at the interactive python console.

Update 1 : I found this link to a Ruby conference keynote where the speaker talks about beautiful code – Ruby is another language that has writing elegant code as one of it’s goals.

Update 2: Here is a great post on why you should spend the time and effort to write beautiful code :-)

Update 3: Here is a website from John Graham-Cumming where one can submit and read beautiful code.

Update 4: A great article on beautiful code by Brian Kernigham

8 comments on “How to write beautiful code

  1. Pingback: How to read code – a primer « Technikhil Writing

  2. Pingback: The Humble Programmer – Edsger W Dijkstra « Technikhil Writing

  3. Pingback: Juggling code – the coding zone and burnouts.. « Technikhil Writing

  4. Pingback: Some great Internet reading « Technikhil Writing

Comments are closed.