These are a few issues that came up during the three code review sessions this past
week. Though not by any means an exhaustive list of important code quality issues,
these issues are worth thinking about when you're revising existing code or
writing new code.
- Try to reduce the cognitive load on your reader. Make things easy to read so
the reader (including you) can spend time thinking about the heart of the problem
instead of about "what does this name mean?" or "where did this variable come from?" etc.
- Strive for simplicity. Sometimes complexity can't be avoided, but usually,
a program can be made simpler. The benefits of simplicity include: easier to understand
(and thus get correct) while writing the code; easier to read and add to or otherwise
maintain the code; greater likelihood that you've mapped the essential concepts of the
problem to suitable code elements; etc.
- Spend time choosing good names. This pays off in readability for code authors and
code maintainers, with benefits similar to those listed above for simplicity. There's lots
of writing on how to choose good names. A few quick principles: avoid vague verbs;
use conventional naming patterns like "is_xxxxx" for boolean-valued functions;
use verb phrases for function and method names; when trying out a name of a function,
try reading it both at the definition of the function, but also at the place where
you're calling the function, to see if it works well there; etc.
- Make each function or method do one thing. (For example, it's good to separate
the code that searches for results from the code that prints those results. That way,
the return value of the search function (that returns, for example, a list of books)
could be used to support further computation, and the print function could be used to
print different book lists. And furthermore, one-task functions are just easier to
read and understand than multi-task functions.)
- When you have something messy like command-line argument parsing, it's best to isolate
that messy computation in a function or a class, and return to the invoking code some sort
of structure (e.g. a dictionary) containing the parsed information that it needs.
- If your programming language or other tools have style guide,
get familiar with its essential features and use the recommended style. This helps in several big
ways: it makes it easy for other programmers to read your code; it reduces the effort you put
into making stylistic decisions when writing the code; it makes it easier to combine contributions
from multiple programmers, since they'll be using a shared style; etc. Python has a widely used style guide
known as PEP 8 - Style Guide for Python Code.