For someone relatively new to the field of programming, the subject of code comments would cause some definite confusion.? That’s because experienced folks in the field can’t seem to agree on the topic.? Some call the practice a code smell?and claim it’s to be avoided.? Yet others tell you to do it.? And still others?strike the middle ground.? Confused yet?? I would be.? At the very least, I’d conclude that it’s a matter of personal taste.
So today, I’d like to offer you something different.? Instead of offering yet another opinion to the mix (though I do have one), I’ll check that at the gate and offer a field guide to code comments.? How did they get here, why do some like them but not others, and what are the different kinds of comments you see?? That way, you can form your own informed opinion, rather than hoping for consensus where none will likely emerge.
What Are Code Comments?
First, let’s level-set a little.? For anyone that’s been programming for a while, this is a bit basic.? But let’s look at what code comments are and what their origin story is.
When you write code, you’re writing instructions.? A compiler or interpreter will take those instructions and turn them into actual commands that an operating system executes.? In order for this to work, the compiler or interpreter requires very specific syntax and semantics.? Code comments exist as a way for you to add free-form text into your code but without the compiler or interpreter paying any attention. This is generally accomplished by using a specific character or characters to indicate code comments, such as “//this is a comment.”? Pay no attention to that text after the double slash!
Why do this?? Well, in the most general sense, it allows you to add meta information to your code and thus to communicate with other programmers (or a future version of yourself).? You can write a line of code and then, after adding the comment character, you can talk about that code.
Where did this come from?? Well, I described its history in detail in this post, but it began as a way to add “remarks” to code that you wrote.? In the early days of programming, many programming languages were extremely terse and littered with GOTO logic, so these remarks were absolutely critical for code readability.
Wait, Why Would Code Comments Be Controversial?
Given what I’ve described, you might wonder why anyone would find this practice controversial.? Wouldn’t it be at worst superfluous and at best really helpful?? Well, that’s certainly the position of proponents of code comments.? And it’s one that makes sense.
To understand the other side of this requires additional context.? First of all, you must understand something about code comments.? Like any bit of code that you write or like unit tests, they require maintenance.? If I add comments explaining what a method does and then I later change that method, I must also change the code comments.? If I don’t, the comments will become out of date and even misleading.? So while comments have utility, they also have cost.
And there’s another important consideration as well.? Since the early days of programming, languages have evolved considerably.? We’ve seen the rise of popular paradigms such as structured, object-oriented, and functional programming.? These have resulted in code that’s easier for humans to follow and to reason about.? Variable and method names have become longer and more descriptive, and this has all given rise to the idea of “self-documenting code”: code so clear that it requires no additional documentation.
The “nay” side of the commenting argument says that comments are a crutch that people use to write unclear code and that their cost and tendency to mislead outweighs their benefits.? The “yea” side of the argument generally counters by citing self-documenting code as a good idea in theory but a pipe dream in practice.? Non-commenters, they argue, claim to write self-documenting code, but they really just leave behind confusing code that they don’t explain.
The Types of Comments People Find Useful
As I’ve said, I’m not going to weigh in with my opinion here.? So if you were waiting for me to plead my case for one side or the other, I won’t.? Frankly, a lot of it is context-dependent anyway.? Some groups may indeed have code that doesn’t require comments for understanding.? Others may get a lot of value out of the comments.? Those groups can both exist in this world at the same time.
So rather than harp on this argument, let me transition into talking about the sorts of comments that groups find beneficial.? In other words, not all groups will want or use these comments, but those that believe in the practice will acknowledge their value.
- Legal disclaimers.? Some companies (usually larger ones) will have policies requiring copyright notices in their files.? These generally occur in the form of code comments.
- Method header documentation.? These comments serve two purposes.? First, they offer context, as any comment does.? But secondly, they allow IDEs to opt into code intelligence, and they can serve as a template for generating documentation.
- Explanations of why.? Not all comments are equally helpful, but there’s broad consensus that these have value.? If you have an unusual situation or design decision, a comment explaining that can help maintenance programmers out a great deal.
- Providing context.? This is kind of an extension of the “why,” but it’s a broader concern.? If there are things maintenance programmers should keep in mind or that might trip them up somehow, provide that context.
The Types of Comments You Should Avoid
Having offered guidance on the comments that maintainers appreciate, let me offer similar guidance on comments that people usually don’t appreciate.? These just add cognitive noise to the codebase without benefit.? I’ve written about this in detail before, so I’ll keep it brief here.
- Restating the obvious.? If you have a while loop that continues while x is less than 10, you don’t need to explain that in a comment next to the while loop.? Assume that anyone maintaining your code can read and write code for themselves.
- ASCII art.? It can be tempting to get cute, but don’t put bunnies or elaborate smileys into the source code.? Take it to Slack or something.
- Excuses or editorials.? Don’t use your source code to explain that this code isn’t your fault or that a stupid project manager is making you rush the feature.? Again, code is not the venue for this (if there is one at all).
- Historical background.? You have source control (I certainly hope, in 2017).? Use source control comments to keep track of the changes to your codebase.? You don’t need a rolling history of who changed this method and when.
- Commented-out code.? Commenting out code is something we all do while troubleshooting or experimenting.? But don’t leave this code when you commit to source control.? Again, your source control system can track what’s been deleted.? Leaving it in will just confuse people and take up space.
Your Strategy for Code Comments
I’ll close by offering some words of advice that I tend to abide by myself.? When it comes to code comments, you’re likely to pick a position and to have an opinion.? I certainly do.? In fact, mine has changed considerably over the years, with me spending time both as an avid commenter and someone who doesn’t bother.
But whatever your opinion of code comments, I’d try not to get too attached to that opinion.? In your travels you’ll find different groups with different norms.? And you’ll find yourself a lot happier and more agreeable if you can adapt to what they do without turning it into a religious war of programming.? So should you comment your code or not?? I’d say, when in Rome…
Learn how GhostDoc can help to simplify your XML Comments, produce and maintain quality help documentation.
[…] A Field Guide to Code Comments – Erik Dietrich […]
It’s worth, as for all writing, considering ‘who is the audience, and when will they read this’. If it is a debug reminder for after a long weekend it could be haphazard. If it’s an awkward context issue for future maintainers, then write clearly.
This then brings up the need for a dual use CM system that allows you to distinguish the mainline commits, from the self-informed haphazard comment debugging commits.
Comments are a way of talking to people… it needs to be done eventually.
Use comments to state intent. It might be obvious that a loop is going to repeat 10 times, but what is the significance of it doing that? Creating a helpfully named constant for the loop number might convey your intent more clearly than the number 10, but for most non-trivial code it really helps the next person along to understand WHY you are doing something.
It seems you forgot “notes to self…” I frequently use code to delimit sections of code and remind myself what that does. I often use TODO to key myself to where things can be improved. Since I work rapidly on many projects in several dialects, I need to do this in order to facilitate switch. I also keep a diary of each project, with notes from each work period. This helps as well–i am old after all…
Love the guideline, just one comment: Sometimes the History is part of the why, specially with old code. Right now I am working on a C++ project that started early 80s, and boy the history has been useful
Comments are essential to understanding code for people joining a project. Not adding comments is lazy, inconsiderate, and wastes peoples’ time (and the company’s time).
I’ve encountered a manager who actually DELETED comments, on the theory that code should be self-documenting. This is like ripping the seat belts out of your car so you will never get into accidents.
You hinted at this with “header comments” but there are two main kinds of comment; describing the interface, and describing the implementation. You should keep these separate, and languages like Python even have two different kinds of comment syntax for them.
Interface comments should focus on making the “contract” clear; preconditions (what it requires), postconditions (what it promises to do), and invariants (what it requires and will not change). They should absolutely avoid any implementation details. Some languages like Eiffel include contracts in the syntax, and meaningful argument names and strong typing help, but there is nearly always something extra needed in comments to make it clear how to use the code without having to look at the implementation. If you find yourself changing an interface comment, it probably means you need to change everything that uses that code.
Implementation comments should be kept to a minimum, avoiding restating things that are already obvious in the code or interface docs. They should only clarify complicated bits and record TODOs.
To quote somebody:
Beginners comment what they’re doing
Intermediates comment why they’re doing it.
Experts comment why they didn’t do it another way.
[…] the SubMain blog, I wrote a guide to code comments.? What kinds of comments help?? What kinds should you […]