Good Code: Part Two of Five – Understandable Code

Welcome back to our five week series, where we explore five aspects of code that should really be fundamental to code being described as “good”. This week we bring you part two. If you missed the first blog of the series, you can catch it here: http://blog.gravitycomputing.co.nz/?p=638

Much of the series is built upon Sara Falamaki’s talk, entitled “Happy Hackers == Happy Code”, which Eric attended at Linux.conf.au 2010 in Wellington.

 

Feature Two:  Good code should be easy to understand.

There is nothing worse than opening up a codebase and finding the code equivalent of Twilight written in Greek.

Good code is set out in a way that is easy to understand, and is accompanied by concise comments that will bring new users up to speed as quickly as possible. If you want your code to be outstanding, try and set it out in such a way that few comments are necessary, and even the most inexperienced of programmers could understand what you are trying to achieve and how this has been done.

If you’re developing a real application, it’s imperative to use self-explanatory variable names.  One of our clients approached us with an application that they’d commissioned a few years back; it had stopped working, and the original developer had left the country.  When we looked into the codebase, every code module started with the line:

dim var_1, var_2, var_3, var_4, var_5, … var_23, var_24, var_25

These variable names don’t mean ANYTHING.  Even the original developer would struggle to identify which variable related to which piece of data.  (“Lets see… Price… I’m pretty sure I stored price in var_12.  Or was it var_21?”). Using meaningful variable names, for example ‘atomic_mass’ instead of ‘aM’ (or even worse, “var_1”), allows everyone to find their way around the code, and understand what is happening with minimal outside reference.

White space and indenting are two more common traits of good code.  It can be very difficult to isolate a particular feature of the code when it is tightly grouped together with other features, so by separating and layering each feature you can make your code more understandable.

Above all else, good code is CONSISTENT. No matter how you choose to name your variables, you should follow the same naming pattern throughout your code. For example, if you decide to start your variable names with an indication of their datatype (sTemp, wsBase, iEndRow, rData) then be sure to stick with that pattern the whole way through. Consistency in what you have chosen is far more important than the actual method that has been chosen.

You can read a bit more about self-documenting code, and making code readable, in the answers to this question on StackOverflow: http://stackoverflow.com/q/209015