def clean_start_year(x):
# Account for the 7 year offset in the database
return x + 7
def process_record(record):
record['start year'] = clean_start_year(record['record'])
It's perfectly obvious what this code does, but without the comment it's totally unclear why it does what it does. const database_year_offset = 7;
fix_start_year(year):
return year + database_year_offset;
process_record(record):
record['start year'] = fix_start_year(record['record']);
In this version with one less magic constant (and renamed function), the comment would look very redundant.DougBTX had the same idea, at the same time. I don't think their version needs the comment either. EDIT: Dang you removed a perfectly fine post :)
Informative comments cannot always be "factored out" like this. Do you at least agree that a ticket or bug #, or a link to an issue in an issue tracker, would be appropriate?
int frob(const int x, void *context)
Performs a frob on x in the given context.
Parameters:
x - int param
context - a pointer to context
Returns an id of the frob performed.The better a variable / function is named (and the better its scope or purpose is limited to one thing), the less it needs comments. So there are a lot of self explanatory variables or functions with doxygen comments that state exactly the same thing the name already does, without adding anything besides noise. And then there are some poorly named things where the exact same thing happens: comment re-states what the bad identifier states. Sigh. Genuinely useful comments are rather rare.
Use your imagination. The "cleaning" routine might not be a one-liner. Maybe it depends on multiple functions from another file/package/library.
Writing the rationale is the most important comment you must not skip.
And there would be links to design documentation so that it can be kept up to date. (For non-programmers.)
This isn't always possible, but it's far more possible than many developers seem to think.
When I read code I care about what the code is supposed to do and why it's supposed to do that.
There is code that passes the current tests and is logically sound but no longer fits the business requirements. Knowing that it was implemented to solve a certain use case helps the reader / reviewer see whether the code and the test still fit or if they should be updated.
The best comments I've come across comment the intention and any context that isn't immediately obvious from the function.
Could I have instead massively restructured the feature to prevent the possibility of the bug the comment was explaining the workaround for? Probably. But that would have increased the number of lines of code to make the change by a factor of something like 20x-200x and would have required far more testing. It also probably would have resulted in something overall more complicated.