I have been a professional programmer at various points in my life (including my current startup)
There are two big problems most programmers face:
- solving the problem in front of them
- working out later what on earth you were doing when you wrote that code
There’s a lot of good advice about the former and not much about the latter.
@Draconis raises a great point about readability, but I would go further.
The key to solving any problem is learning the context. But, once you move on, the context starts to get fuzzier and fuzzier until you lose it completely. Then, absent that context, many contemporaneous notes become unreadable.
Make the context as explicit as possible.
Comments are often brought up but I’ve read far too many comments that were absent any relevant context and therefore incomprehensible when read later.
Let’s take an all too common example:
// set the initial value of “ms” to 1
ms = 2
Setting aside that the comment is a long winded repetition of the code and adds nothing but maintaince burden, what was so special about the value 1? Obviously at some point it got changed to 2. Why? Was that in error? What does any of this mean? It’s very frustrating when you know you that past-you wrote this.
I’m simplifying the example to absurdity in order to get over a point.
In my work I typically try to use functional languages and write functions so small their own name is documentation enough to convey a context.
If I am going to the trouble of leaving a comment I try (and often fail) to communicate the context and intent of what is going on. Here’s the same example again:
// the allocation strategy can be 1 or 2
// depending upon whether we have high or
// low memory. For low memory configs
// it should be 1
mem_alloc_strat = 2
A stupid off the cuff example but the idea is that in the future there is a clue as to the reasoning behind whether this value is 1 or 2 and why it matters. Are we crashing with memory errors? Perhaps try going back to 1 and see if solves the problem.
If we go back to the earlier example. At the time we wrote it, it was obvious that ms
was referring to the memory strategy and that 1
was the low-memory strategy and 2
was the high-memory strategy. It was so obvious that we clearly didn’t need to write it down at the time. And so it goes.
This stuff is hard and doesn’t seem to get much easier. The state of the art does not seem to have advanced much since I started writing code in the ‘80s.
Be careful out there folks and come home safe.