Mar 012011

Download as ebook

Lately my colleagues have been commenting on my relentless notes on code styling in our internal code-reviews. Evidently I’ve been paying more and more attention to what could rightly be called cosmetics. Sure there are bad conventions and, well, better ones. Admittedly, coding conventions are just that, conventions. No matter how much we debate tabs vs. spaces and how much we search for truth, they remain subjective and very much a personal preference. Yet, one can’t deny that there are some better conventions that do in fact improve the overall quality of the code.

But code quality is not what worries me. Not as much as worrying about eye strain and accidental misreadings. Both of which are also factors in the overall code quality, no doubt. It’s not rare that we find ourselves agonizing over a mistake that if it weren’t for haste and misunderstanding, could’ve been completely avoided.

C Sample Code: Function Parameter Duplication.

Image via Wikipedia

Developers don’t write code, not just. We spend the majority of our time adding, removing and editing small pieces of code. In fact, most of the time we do small changes in an otherwise large code-base. Rarely do we write new independent pieces of code, unless of course we are starting a project from scratch. Most projects are legacy projects in the sense that they are passed from generations of developers to the next. We add new functions to implement new features, rewrite some and edit some others to meet our needs. All of which means reading a great deal of code to understand which statement is doing what and decide the best change-set to get the output we plan. But even when we work on a completely independent module or class, once we have the smallest chunk of code written, we already need to go back and forth to interweave the remaining code.

Oddly, as I grew in experience I also spent increasingly more time reading code before making additions or changes. This seems reasonable in hindsight. It’s much easier to write new code, much more difficult to try to understand existing code and to find ways to adapt them. Experience tells us that the easiest route is not necessarily the best in the long run. Sure, we might get faster results if we write that case-insensitive string comparison function for the 30th time whenever we need one, or so we might think. But the fact is that chances are that we’ll get a few incorrect results as well, which we might not even notice until it’s too late. With a little effort, we should find a good implementation that we can reuse and learn how to use it. Indeed, that implementation might very well be in our code-base. My example of string comparison is not all that artificial, considering that some languages don’t come with standard string comparison functions, with Unicode, case and locale options. Some languages do have standardized (or at least canonical) functions, but you need to explicitly include the library reference in your projects and that might involve SCM and build server issues. Not fun when the deadline is looming, and when exactly was the last time we didn’t have an imminent deadline? (Notice that I do not mean to imply that DIY coding is a deadly sin. It probably is in most cases, but surely there are good reasons to write your own. Like early optimization, the first two rules are don’t do it. But that’s another topic for another day.)

Another great side-effect to reading code is that one will eventually find bugs and at least report them, if not fix them on the spot (and send for review). So instead of creating new sources of bugs, reuse reduces code duplication and possibly resolves old bugs.

When we anticipate and reasonably-accurately estimate the overhead of possible bugs in our home-grown functions, scattered around the code-base, in comparison to the overhead of learning and incorporating a higher quality library function, then and only then do we stand a chance of making reasonable decisions. Unfortunately, understanding the difficulty of such comparisons and especially grasping the perils of code duplication combined with the Dunning–Kruger effect when it comes to estimating expected bugs in one’s own code, requires, paradoxically, experience to become obvious.

The whole issue of maintaining legacy code vs. writing from scratch is a different battle altogether. However, I will only say that improving on legacy code in any pace is almost always superior to the demolition approach. It’s less risky, you still have working bits and pieces and you have a reference code right on your plate. And here is my point: to avoid rewriting, one must learn to read existing code, and read them well.

To make things more concrete, here are some of my top readability points:

  1. Consistency.
    I can read code with virtually any convention, no problem. I’ve grown to learn to adapt. If I think I need to read code, then I better accept that I may very well read code not written in my favorite style. One thing that is nearly impossible to adapt to, however, is when the code looks like it’s written by a 5 year old who just switched from Qwerty keyboard to Dvorak.
    Whatever convention you choose or get forced to use, just stick to it. Make sure it’s what you use everywhere in that project. 

  2. Consistency.
    There is no way to stress how important this is. People experiment with braces-on-next-line and braces-on-same-line and forget that their experiments end up in the source repository for the frustration of everyone else on the team. Seriously, experimentation is fine. Finding your preferred style is perfectly Ok. Just don’t commit them. Not in the Trunk at least. 

  3. Space out the code.
    Readable code is like readable text. As much as everyone hates reading text-walls, so do developers who have to read sandwiched code. Put empty lines between all scopes. An end-brace is a great place to add that extra line to make it easier to read and find the start of the next scope. Need to comment? Great. Just avoid newspaper-style coding, where the code is turned into a two-column format, code on the left, comments on the right. There are very few cases that one needs to do that. Comments go above the code block or statement, not next to it. Comments are also more readable if they are preceded by a blank line. There is no shortage of disk space. Break long functions, break mega classes and even break long files. Make your functions reasonable in size. Use cyclomatic complexity metrics to know when your code is too complex and hence hard to read and understand. Refactor. 

  4. Stop banner-commenting.
    If you need to add 5 lines of boxed comments within functions, then it’s a good indication you need to start a new function. The banner can go above the new function. As much as I’d rather not have it there either, it’s much better than having a 1000+ lines in a single function with half a dozen banners. After all, if you need to signal the start of a new logical block, functions do that better. Same goes to breaking long functions, classes and files. (Unlike what the image above may imply, that image is just an image of some code, I do not endorse the style it adopts.) 

  5. Don’t use magic numbers.
    Constants are a great tool to give names to what otherwise is a seemingly magic number that makes the code work. Default values, container limits, timeouts and user-messages are just some examples of good candidates for constants. Just avoid converting every integer into a constant. That’s not the purpose of constants and it reduces code readability. 

  6. Choose identifier names wisely.
    There has been no shortage of literature on naming conventions and the perils of choosing names that lack significant differences. Yet, some still insist on using very ambiguous names and reuse them across logical boundaries. The identifiers not only need to be meaningful and unambiguous, but they also need to be consistent across functions, classes, modules and even the complete project. At least an effort to make them consistent should be made. If you need to use acronyms, then make sure you use the same case convention. Have database or network connections, use the same identifier names everywhere. It’s much, much more readable to see an identifier and immediately know what the type is. Incidentally, this was the original purpose of Hungarian notation (original paper). Same goes to function names. ‘Get’ can be used for read-only functions that have no side-effects. Avoid using verbs and nouns in an identifier then implement logic that contradicts the natural meaning of those words. It’s downright inhumane. If a functions claims to get some value, then that function should never modify any other value (with the possible exception of updating caches, if any, which should only boost performance without affecting correctness.) Prefer using proper names in identifiers. Meaningful names, nouns and verbs can be a great help, use them to their limit. 

  7. Don’t chain declarations.
    Chaining variable declarations is a very common practice in C. This is partially due to the fact that Ansi C didn’t allow declaring variables after any executable statement. Developers had to declare everything up-front and at the top of their functions. This meant that all the variables of a given type were declared in a chain of commas. Declare variables in the innermost scope possible and as close to the usage statement as possible. Avoid recycling variables, unless it’s for the very same purpose. Never re-purpose variables, instead, declare new ones.
    A similar practice is sometimes used to chain calls where a single function call which takes one or more arguments is called by first calling other functions and passing their return values as arguments to the first call. These two types of chaining make readability a painful process. Some people chain 3 or 4 function calls within one another, thinking it’s more compact and therefore better, somehow. It’s not. Not when someone needs to scan the code for side-effects and to find a hard bug. A possible exception to this is chaining calls one after another. Some classes are designed to chain calls such that each call returns a reference to the original instance to call other members. This is often done on string and I/O classes. This type of chaining, if not excessively used and too long, can be helpful and improve readability. 

  8. Limit line and file lengths.
    Scrolling horizontally is a huge pain. No one can be reasonably expected to read anything while scrolling left and right for each line. But some people have larger screens than others. Yet some have weaker eye-sight, so use larger fonts. I’ve seen code apparently aligned to 120 characters per line, with occasional 150+ characters per line, back when 17″ screens were the norm. Some don’t even care or keep track of line length. This is very unfortunate as it makes other people’s lives very hard, especially those with smaller screens, lower resolutions and large fonts (read: bad eye-sight.) Code can’t be word-wrapped like article text (without the help of advanced editors.)
    A good starting point is the legacy standard of 80 characters-per-line (cpl). If we can stick to that, great. We should make an effort to minimize the line-length and 80 characters is not too narrow to make things garbled. For teams who can all work with 100 or 120 cpl, the extra line width can give quite a bit flexibility and improve readability. But again be careful because too long a line and readability suffers yet again. Think how newspapers and magazines have narrow columns and how readable they are. Our wide screens with large footprints are like newspapers and moving our heads to read across the line, as opposed to moving just our eyes, is an extra physical strain and certainly a speed bump that we can do without. 

  9. Make scopes explicit.
    Languages often have implicit scopes. The first statement after a conditional or a loop in C-style languages implicitly fall under the conditional or loop, but not consecutive statements. It’s much harder to parse the end of statements using one’s eyeballs to figure out which statement belongs to the implicit scope. Making these cases explicit makes it much easier to see them without much effort. Adding braces and an empty line after the closing brace, even around single-statement scopes does improve readability quite a bit. 

  10. Comment.
    Code is very well understood by machines, even when obsecure and mangled. Humans on the other hand need to understand purpose and reason, beyond seeing what a piece of code would do. Without understanding the reasons behind particular constructs, operations and values, no developer can maintain the code in any sensible way. Comments are a great tool to communicate the less obvious aspects of the code. Explain the business needs, implicit assumptions, workarounds, special-requests and the temporary solutions. Talk to your fellow developers through comments. But, as every rule comes with exceptions, avoid over-commenting at all costs. Resist the temptation to declare that an error is about to occure right before throwing an exception. The throw statement is self-commenting. Don’t repeat yourself. Rather, explain why the case is considered unrecoverable at that point, if it’s not obvious. Prefer to write code that speaks for itself. Self-descriptive code is the most readable code.

As a corollary, some code should be made hard to read. You read that right. Code that depends on hacks, bad practices or temporary solutions should be made harder to read. Perhaps my best example is casting. It’s not rare that we need to cast instances of objects to specific types, and while this is a standard practice, it isn’t exactly highly recommended either. Making the casting a little less readable is a good way to force the reader to squint and make sure it’s not a bogus cast. This isn’t unlike italic text which makes reading the text harder and therefore makes it stand out. In the same vein, temporary solutions and hacks should be made to stand out. Adding TODO and FIXME markers are a good start. BUGBUG is another marker for known issues or limitations. Actually, if there is any place for that banner-comment, this would be it. Make known issues stand out like a sore thumb.

As with most things, the above is mostly a guideline, rules of thumb if you will. They are not set in stone and they aren’t complete by any stretch of imagination. There are many obviously important cases left out. Languages, ecosystems, frameworks and libraries come with their own nuances. What’s clear in one language might be very ambiguous in another, and therefore frowned upon. The important thing is to write with the reader in mind, to avoid confusing styles and especially to be mindful of the context and when an explanatory comment is due, and when refactoring is a better choice.


Good developers write code fast and with low bug-rate. Great developers read existing code, reuse and improve them, generating higher quality code with no duplication and reduced bug-rate for both new and existing code. We should write readable code; written for humans and not just for machines. And we should read code and improve, rather than rewriting.

Download as ebook


  30 Responses to “Why Code Readability Matters”

  1. Hidden due to low comment rating. Click here to see.

    Poorly-rated. Like or Dislike: Thumb up 10 Thumb down 43 (-33)

    • Since I hadn’t tried, I thought I should at least fail once before giving up. Plus, I might find out that I’m not really alone after all.

      Highly-rated. Like or Dislike: Thumb up 11 Thumb down 1 (+10)

    • Ash – you’re not alone. It’s incredibly important to write readable code especially within large team environments and the guidelines you posted here are very valuable.

      Highly-rated. Like or Dislike: Thumb up 5 Thumb down 1 (+4)

      • Thanks Adi! Indeed they become absolutely critical the larger the project and team.

        Like or Dislike: Thumb up 2 Thumb down 2 (0)

    • Gekkor, you sound like you’re ranting. What is the purpose of ranting like this? You cannot succeed to convert people to think like yourself, so why bother?

      Hot debate. What do you think? Thumb up 5 Thumb down 3 (+2)

  2. I agree with much of what you say. Especially when it comes to function naming. I would rather have a verbose naming convention over acronyms and abbreviations any day. When you come back to a project months or years later, it makes it infinitely easier to understand the code again.

    Conventions as well. It really doesn’t matter what conventions you use, as long as it is internally consistent in the project. Nothing worse than a project using a mix of underscores and camelcasing, for example.

    Like or Dislike: Thumb up 3 Thumb down 2 (+1)

  3. What is your opinion of tools like gofmt that can be used to rewrite sources to enforce style guidelines and that can invoked via precommit hooks or to give warnings on certain kinds of style convention violations? Effective go says “Formatting issues are the most contentious but the least consequential. People can adapt to different formatting styles but it’s better if they don’t have to, and less time is devoted to the topic if everyone adheres to the same style. The problem is how to approach this Utopia without a long prescriptive style guide.”

    Like or Dislike: Thumb up 0 Thumb down 1 (-1)

    • Tools and commit hooks have been used successfully for quite some time. I’m sure they are a great help in many cases. The best case that I can think of that works seamlessly is the conversion of end-of-line chars. However the more complex the conversion, the less the success rate. Even converting tabs and spaces can have side-effects. Some (many?) who use tabs also mix spaces to improve alignment. Automatic conversion in such cases will probably skew hand-aligned code.

      Bottom line is, automate as much as possible, but know the limitations beforehand. And limitations they all have. Most importantly, don’t replace good practice with automation or otherwise. It’s always a good idea to type-out well-formatted, readable code than to rely on other factors. Especially when you change jobs, projects or the editor.

      Like or Dislike: Thumb up 1 Thumb down 1 (0)

  4. This is so much helpful! Congrats for the article.

    This quote says everything:

    “We should write readable code; written for humans and not just for machines.”

    Like or Dislike: Thumb up 1 Thumb down 1 (0)

  5. > I’ve seen code apparently aligned to 120 characters per line, with occasional 150+ characters per line, back when 17″ screens were the norm.

    At the company I recently left, they had their line wrapping set to 1000 columns in eclipse. When saving conditional statements would be wrapped to 1 line. There were lines where you had to scroll for 800 columns in the projects I had inherited. It upset me greatly to no end.

    The bizarre reasoning for this was not blatant stupidity(tho I dare not rule it out) but 1 of my coworker’s eye sight was rather poor and the cost of purchasing a 24″ or 27″ monitor, meant the 8 other devs would have to suffer. Sacrifice the code base because the company is too tight fisted to properly equip an employee with special needs. Utterly bizarre.

    Like or Dislike: Thumb up 0 Thumb down 1 (-1)

  6. Spacing out code and limiting line lengths are well supported by current models of source code readability. The other confounding factor is information content, really means, number of tokens and number of unique tokens, so if you can say something very concise you can often gain a lot in code readability. It’s interesting how this enforced elegance can increase readability.

    Like or Dislike: Thumb up 0 Thumb down 1 (-1)

  7. “I can read code with virtually any convention, no problem. ”

    Then whats the point of dogmatic consistency?

    Like or Dislike: Thumb up 0 Thumb down 2 (-2)

    • A convention still has to be consistent to be readable. Any convention doesn’t mean any mix of conventions thrown together, rather it means any convention, provided it’s consistent across the project.

      Like or Dislike: Thumb up 2 Thumb down 1 (+1)

  8. “Adding TODO and FIXME”

    I have never worked at a place that didn’t have a bug tracking system. If you put TODO’s and FIXME’s in your code you are the type of person I absolutely do not want to work with. It means you aren’t finishing the job. Put a ticket in which explains why the code is not correct or what functionality is not complete. But don’t commit a TODO to fix some thing “later”, because any software developer worth 1/10 of their salt knows there is absolutely never a “later”.

    Like or Dislike: Thumb up 2 Thumb down 1 (+1)

    • Bug tracking and TODO/FIXME aren’t the same thing. Bug tracking tracks user-visible, business oriented issues. TODO/FIXME are marker/helpers for developers to be aware of internal design issues. They overlap, coincide and are related to one another. But they can’t completely replace one another. Unless you create bugs that describe which function needs to get a new case to handle a certain value of a certain member when the user hits a certain button, that detail is implementation specific and should go in the code and code documentation. The bug tracks the feature or lack thereof.

      FIXME is added to note that the code doesn’t support a certain case that is never required by the business reqs (hence no need to create a bug,) but the limitation would be helpful to note for the benefit of future developers. This limitation should also be added in the design documentation.

      There are other cases too. But having said that, my point is that when/if we have to make notes on limitations, we should make them stand out. I’m not suggesting we replace bug tracking with in-code TODO and FIXME. Rather, I’m saying that when/if we must have them, we should make them as noticeable as possible.

      Highly-rated. Like or Dislike: Thumb up 5 Thumb down 1 (+4)

  9. Consider using literate programming.
    If you have code that lives forever and the company
    depends on the code it is worth investing in writing
    the code so people can read it like a novel.

    Like or Dislike: Thumb up 0 Thumb down 1 (-1)

  10. Commenting is good. Helps me who test the software and debug a LOT. But I hate when I see excessive use of ‘*’ like the OP has used. Keep the comments neat.

    Like or Dislike: Thumb up 1 Thumb down 1 (0)

  11. Good post. $post =~ s/peaces/peices/g;

    Like or Dislike: Thumb up 0 Thumb down 1 (-1)

  12. […] Why Code Readability Matters » the VoidLately my colleagues have been commenting on my relentless notes on code styling in our internal code-reviews. Evidently I’ve been paying more and more attention to what could rightly be called cosmetics. Sure there are bad conventions and, well, better ones. Admittedly, coding conventions are just that, conventions. No matter how much we debate tabs vs. spaces and how much we search for truth, they remain subjective and very much a personal preference. Yet, one can’t deny that there are some better conventions that do in fact improve the overall quality of the code. […]

    Like or Dislike: Thumb up 0 Thumb down 1 (-1)

  13. […] automation is code, so Why Code Readability Matters is important. Especially since a large body of people writing automation would not consider […]

    Like or Dislike: Thumb up 1 Thumb down 1 (0)

  14. When I started to learn electronics my problem was that I looked at the circuit as one large block, and the same thing with software you need to make clear what each module does, why it is here, and why it is designed the way it is.

    Like or Dislike: Thumb up 0 Thumb down 1 (-1)

  15. Hidden due to low comment rating. Click here to see.

    Poorly-rated. Like or Dislike: Thumb up 0 Thumb down 3 (-3)

  16. Hidden due to low comment rating. Click here to see.

    Poorly-rated. Like or Dislike: Thumb up 0 Thumb down 3 (-3)

    • Haven’t tried PVS-Studio, but I have worked with different static analysis tools on different languages. I must say they do help a lot for virtually all mechanical checking cases. Identifier names, indentation, braces. But not only, they can also help with exceptions, best practices etc. But they are limited when you need rules that can’t be strict. For example, when is someone over-commenting? Some algorithms need more comments than others. Sometimes there is no need for any comments, and requiring comments just forces everyone to write garbage for comments just to satisfy some tool.

      Some things it seems are very hard to automate, and indeed there is less need the better the team is. I prefer to work with a team of professional and well-rounded developers without any automated tools any day, than to work with the best tools and the antithesis of the former team.

      Like or Dislike: Thumb up 0 Thumb down 1 (-1)

  17. very good put up, i actually love this website, carry on it

    Like or Dislike: Thumb up 0 Thumb down 1 (-1)

  18. […] the details". When that happens, here's some things that I think about when deciding: K.I.S.S Is it readable? Next time you're unsure of a design decision/direction, come here with it and what you're leaning […]

    Like or Dislike: Thumb up 0 Thumb down 1 (-1)

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


(required, not public)


QR Code Business Card