Rules for writing readable code
This is written long time back in 2000 or so. I recently updated and made it into a different article. I think people still may find it useful.
Boiling down to essentials, the rules for writing readable code can be stated as the following:
- All the lines have to be limited to 80 characters long.
- Only one statement is allowed per line.
- Do not leave unnecessary blank lines.
- Do not use tab character. Convert tabs to spaces (most of editorsprovide this option).
- Align the new line with the beginning of the expression at the same level on the previous line. i.e. Do block related statements together.
- Indent 2 spaces for each block and all continuation lines have to be indented.
- Understand that at any moment, user can read only 25 or so lines of code.
So, organize that code around that fact. That means:- Have functions that are smaller than 25 lines. Best way to create new functions is to abstract some part of the problem (domain, echnical, or linguistic) and provide a function for that. It always should be possible to get such an abstraction going.
- If the function is large, break down into blocks, where each block is doing some unique activity. Use one line comment describe that activity.
- Use appropriate formatting scheme to cut down on excessive lines. For examples, ornate commenting scheme is not good. Placing empty lines that does not indicate some semantic separation to the reader is not good. Also, use K&R scheme of indenting to maximize the information to lines ratio.
- For complex logic functions, include the algorithm before the function body and after the comment section.
- Understand that code is meant to be read and understood. That means, it
should be readable, say, over the phone. That means:- Use meaningful names. Long names are not necessarily the most meaningful. It is ok to use i and j for indexing. If there is an abbreviation, such as num, no etc. use one unique abbreviation through out the project.
- Use verbs in naming procedures, because it indicates action. Use names for functions that return values.
- Never, ever use two names that differ only in capitalization, and punctuation.
- Comments should not repeat the code. Comments are meant provide higher-level road map. That means:
- Comments should explain the domain portion, not the code.
- Comments should tell the reader why and what you are doing it, rather than how.
- In case the code is tricky, explain the how, and tell them explicitly why it is tricky.
- Use commenting style that is easy to maintain.
Unfortunately, lot of books concentrate on the concrete than the abstract. For full details, read other related articles on this site.