Sometimes I write code that works correctly, but when I revisit it a few days later, I struggle to remember what I was trying to do. What practices help most with maintainability: clearer variable names, smaller single-purpose functions, comments, formatting tools, or something else?
5 Answers
Comments can also document the program's state at important points. For example, noting that a buffer contains a raw line or that a token is the first comma-delimited field makes assumptions explicit. This is especially helpful when the details aren't obvious from the function names or data types.
Start with clear names and functions that do one focused thing. If a function handles several unrelated tasks, split it up and name each part based on its purpose. Comments are most useful when the code alone can't explain something, rather than simply describing obvious operations. Also, don't be too hard on yourself—older code can feel like it was written by a stranger.
The most valuable comments explain why a choice was made, not what the code is doing. The code already shows the steps, but it usually won't explain that a less-obvious approach was chosen because a normal solution failed in a particular browser, environment, or edge case. Recording that reason can prevent someone from “fixing” the code back to a broken version.
Make the code describe itself wherever possible. Descriptive names, small functions, consistent formatting, and standard linting rules all make unfamiliar code easier to scan. Comments should add missing context, especially around unusual behavior or important constraints, instead of repeating the syntax.
Sometimes giving a value its own descriptive variable is worthwhile, even if it adds a line or two. A name such as MAX_THRUST or isQuantityValid can make the intent much clearer than embedding a number or a complicated condition directly in another expression. Refactoring helps too, but first make sure you understand what the existing code is meant to accomplish.

That makes sense. The reason behind an unusual decision is usually the first thing I forget, even when the implementation itself is readable.