A Field Guide to Code Comments
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.