[Better Developers #2] When and how to comment code
Issue #2 · Full archive
When and how to comment code
Coming up at LernerPython
- The 10th cohort of PythonDAB — my 18-week Python, Data, and AI bootcamp — starts on November 5th. Full info.
- Free info session on Tuesday, October 27th: register here.
- All upcoming LernerPython events.
Hi there! This is the first of what should be weekly tidbits about programming. Most of them will be relatively short, talking about a single topic that I think is useful or important. Many of these topics come from students I've taught, which means that the topics will often be about Python, Git, PostgreSQL, or data science. But I'll mix in some bigger ideas, some new technologies that I've been playing with, and some general advice. This newsletter should come out every Monday. News about events, including Webinars and announcements of new courses and books, will come in separate "announcement" messages.
If you want me to cover a particular topic, please don't be bashful: Reply to this message, and I'll read what you sent. More than half of what I teach is the result of questions from students!
This week, we'll talk about comments.
One of the first things that programmers learn is that they should put comments in their code. Each language has a different comment syntax; in both Python and Ruby, a comment consists of a # mark until the end of the line — a syntax borrowed from Unix shell scripts.
The trouble with too many comments
New programmers tend to write lots of comments — indeed, too many comments. Moreover, they tend to write bad comments. The combination of many, bad comments leads to software that's hard to maintain, because you have to (a) find the code between the comments, (b) read the comments, and (c) ignore many of the comments. Worse yet, it's common to update the code without updating the comments, leading to clear conflicts between what the comments say and what the code does.
Let's start with what a a description of good comments: As the old saying goes, you comment why, not what. Here is an example of a bad comment:
# Reset the random seed
random.seed()
The above comment is ridiculous; if you cannot understand that random.seed() is resetting the random seed, then writing a comment to that effect won't help, either. In this case, the comment is telling us what the program is doing, but reading the code reveals just as much.
There are more complex examples of the same phenomenon:
# Find the first user whose first name matches the search string
for one_user in users:
if one_user['first_name'] == search_string:
print("Found it!")
break
Again, if you don't understand what a for loop does, then you probably shouldn't be mucking around with this code. And if you do, then the comment probably didn't do much to enhance your understanding.
In both of the above cases, the comment was a "what" remark — telling us what the code was doing, even though it was quite obvious from reading the code. I've seen oodles of such comments over the years, and much as I'm ashamed ot admit it, I'm guilty of having written such things, too.
Comment the why, not the what
So, what would be a good comment? Again, your comments should say why you're doing something, rather than what you're doing. For example, let's take the above example:
# Once users are in memory, it's faster to search through them than to hit the database again
for one_user in users:
if one_user['first_name'] == search_string:
print("Found it!")
break
The above comment doesn't even try to answer the question of what the code is doing. It assumes that you know, and that you're asking why it was decided to write it in this way. The comment tries to answer that question. Comments often reflect business objectives and decisions, or coding decisions that might seem odd to someone looking at the code for hte first time.
Once you start thinking in terms of "why" rather than "what," many comments suddenly seem unnecessary. In some cases, you can remove comments by using better variable and function names, which make the code somewhat self-documenting. I'll talk about this in a future newsletter, but choosing good function and variable names can make a big difference in the readability of the code — and thus reduce your temptation to put comments in there, as well.
I've occasionally heard people say that we should remove most comments. That's an extreme viewpoint, but I can understand why they say it: So many comments are useless that it's almost better to leave them out entirely. I'm not in favor of getting rid of all comments, but I do think that you should see comments as a last resort, describing code that better names and better structure cannot explain alone.
Who actually reads your comments
Finally, remember who is going to read your comments: In all likelihood, it'll be someone under the gun, trying to debug your code in the wake of a problem that needs to be fixed. Try to consider what they'll be looking for, or what might be confusing or non-obvious to them. Guide them to the parts of the code that might be confusing. Remembering that your comments' customers are the developers who will be maintaining your program. This includes yourself; I'm sure that I'm not the only developer to have read through some code and comments, wondering which of my idiot colleagues had written that junk, only to discover that the idiot in question was myself.
Until next week,
Reuven
To make sure that these messages get to your inbox (and aren't tagged as junk or spam), please add [email protected] to your address book, or whitelist it.
To select which messages you get from me, or just unsubscribe from all of my content, click here: https://www.getdrip.com/subscribers/dovhkapguv9rkaauh819/topics?exclude_click=1&edit_details=1
My company's address: 404 Rices Mill Road, Wyncote PA 19095 USA