How to write understandable code?

There is a simple principle: to understand code easily, you must be able to read it like a text.

The basics of writing such code is to write code lines that could be read like English natural language sentences, and then actually mean what your code means. This is much about naming variables and methods in a way so that they fit into the “sentences” when readin them. But there is more to writing code like a text:

  • Principle: Your code must not utilize knowledge that will appear later in the “text”. (Except in the exceptional case where you explicitly put a reference to it, using a code comment.) For each source line, the “previous text” that you can assume to be known content is this (here referring to typical Java code):
    • documentation’s intro page for the whole library or application
    • package.html Javadoc for the current package and up to the root package
    • Javadoc doc block of the current Java element (method or attribute, plus interface or class)
    • Javadoc doc blocks of all Java elements appearing in the current method (if we are in a method of course)
    • source code incl. source comments of the current method
  • Principle: Writing source code as a well understandable text also means to not use excessive nesting, that is, to dissolve such sections by re-structuring the code. As a basic rule, avoid more than 4-5 nesting levels within a method body. Creating objects of anonymous classes adds to the nesting level, but using an inner class does not.

This idea of “writing source like texts” was mine, but I’m sure more developers got it and practice it. But also, I did not read about this in any book, and I’m also sure that there are more tips and details to it than presented here. So if you make more observations, you’re welcome to add them in the comments!


Posted

in

,

by

Tags:

Comments

2 responses to “How to write understandable code?”

  1. David Zokaites

    I agree with you completely! As a matter of fact, this topic is so important to me I published an article on it. My article is “Writing Understandable Code” by David Michael Zokaites available at

    http://drdobbs.com/windows/184414802

  2. David, thanks for sharing, that’s a good read! Seems like you got the same idea, but way earlier than me. Also you elaborated it more … reminds me that I have more to say on this, it’s currently burried in notes somewhere.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.