I try to use comments only as a last resort.
Some of my personal tricks for not getting confused by my own code (in order of importance):
0. If you cannot tell immediately what a piece of code does, you need to rewrite it.
1. If you cannot tell what a variable stands for by its name you have to rename it.
2. Two pieces of code doing the same thing are not tolerated: one of them must go.
3. No change serving clarity may be denied on the basis that it will require a lot of work. Postponing such changes is allowed but only with a great feeling of guilt.
4. Similar actions for different objects must have similar (possibly identical) names.
5. Similar actions for different objects that can be templated-in should be templated in, and the repeating code eliminated. Here having the same names for similar actions on different objects may actually play an essential role.
6. I try to split longer functions into smaller steps. Even if there is no clear logical separation in phases, I often split just to increase readability. I have functions with names such as ComputeSystemStep1, ComputeSystemStep2, etc.
7. I try to write code with minimal indentation. My only reason is I find such code more readable. For example, I would prefer:
1 2 3 4 5 6 7
|
if (extra_special_condition_holds)
{
handle_extra_special_condition();
return false;
}
handle_regular_case();
return true;
|
rather than
1 2 3 4 5 6 7 8 9
|
if (extra_special_condition_holds)
{
handle_extra_special_condition();
return false;
} else
{
handle_regular_case();
return true;
}
|