Comments
This part is almost straight from my programming style document.
This might sound stupid, but try to comment every other line (unless you have a lot of repeating or similar tasks). By doing so you get two advantages:
- Someone unskilled in programming or unfamiliar with what you are doing is able to read your code.
- You know what you are doing
The first advantage is important unless you are working alone and never expect to see your code again. In that case you should really ask yourself if you should even be writing that code.
The second one is important even if you have no trouble reading code. Let's take a look at the following example.
for(int index_person = 0; index_person < persons.size(); ++index_person)
{
for(int index_kids = 0; index_kids < persons[index_person].kids.size(); ++index_kids)
{
/* ... */
}
}
And then take a look at this example:
/* Iterating through the persons in the lists */
for(int index_person = 0; index_person < persons.size(); ++index_person)
{
/* Iterating through the kids of the persons in the list */
for(int index_kids = 0; index_kids < persons[index_person].kids.size(); ++index_kids)
{
/* checking if any of the persons in the list have a kid who is dead */
/* ... */
}
}
In the last example I only have to track back to the first comment prior to my line of code to know what I'm doing here. It's a pain to write so many comments but it makes code a whole lot easier to read.
September 2nd, 2010 - 08:38
Did you also see the bug in this code? Take a look at the second loop, where you try to get something from the persons vector(?) but have typed ‘person’
September 2nd, 2010 - 09:05
Fixed it. Although the article was more focused on how to use comments