Improving Code Readability

Yuval Adam picture Yuval Adam · Feb 15, 2009 · Viewed 12.5k times · Source

When it comes to code documentation, it is usually accepted that code should explain itself, and inline code documentation (excluding public API documentation) should only explain meta-code issues such as workarounds, explanations on why specific implementations were chosen, etc.

How do you accomplish making your code more readable and more explaining itself?


Edit: in addition to general comments, I'm also looking for specific tips. So if you say "short but meaningful variable names", it would be nice to also get a helpful tip as well (e.g. "use the three-word principle").

Answer

cletus picture cletus · Feb 15, 2009

Check out Jeff Atwood's Code Smells blog post. It pretty much sums it up. I'll add my personal ethos when it comes to good readable code:

  • Consistency: this applies to formatting, using braces, naming (variables, classes, methods) and directory layout (if you bury a source directory somewhere under /css I'm coming after you with a machete);
  • Size: if a function doesn't fit in its entirety on the screen in a normal IDE at a normal font size then you need a pretty darn good reason as to why not. Of course there are some valid cases for much longer functions but they are greatly outweighed by the egregious examples. Decompose as necessary to keep your functions simple;
  • Comment Judiciously: there is a tendency for some programmers to use comments as a substitute for readable code or to simply comment for the sake of commenting (like /* finished */ comments right before return true;. Seriously, what's the point? Most (good) code explains itself;
  • Never Cut and Paste Within a Project: it's perfectly acceptable to take a code snippet from one project to another (every project is an island) but you should never take a non-trivial code segment from within one project to some other point within the project. Inevitably one changes and you leave some poor developer with the task of looking at these two or more code segments trying to work out how (and arguably more importantly, why) they are different; and
  • Avoid Repetitive Code: if you find yourself writing the same sequence of statements (or very similar) over and over again, abstract or parameterize it. If you see very similar statements the tendency is to skim over them assuming they're all the same (when typically they won't be in a way that matters).