Writing Comments in a Good way
by Pabashani Herath
All the knowledge from this series is based on Robert C. Martin’s “Clean Code.” I hope I can encourage people to read this book and write better codes in this way.
In our code and code formatting, I will discuss commentary in this post. My aim is to try and figure out when we are supposed to add comments to our code. Because developers need to read the code every day, we have to use a good design style to make it easier to read it.
// It works on my machine
// ¯\_(ツ)_/¯
"Don’t comment bad code — rewrite it." — Brian W. Kernighan and P. J. Plaugher
Bad code is one of the most common reasons to write comments. We write a module and we realize it is disorganized and confusing. This is a mess, we realize. And we’re telling us, “Oh, I‘d like to comment better! “Actually, not so! You better clean it! You better clean it!
Simple and concise code with a few remarks is much superior with multiple comments to cluttered and complex code.
"Instead of wasting your time writing the comments that describe your mess, spend cleaning up this mess."

Nothing like a nice comment can be so helpful. Nothing more than meaningless dogmatic remarks can cover a module. Nothing could be as harmful as a nasty old message, which propagates lies.
It’s time to discuss coding comments. I think that three things can be generally: good, bad, and funny (especially if you don’t have to deal with it). Now, let’s think of the comments “ What kinds of problems are focusing on? ”.
We can rapidly modify and test software behavior, even in production.
Software licenses can be entered in the code.
We can supply some information to a different developer etc.

If we consider comments in code, we have comments in mind which clarify what the code is doing. The challenge with comments is they are not always published. The code is modified quite frequently, but the old comments are similar. Therefore, the comments no longer represent the code.
"The best comment is a good name for a method or class."
Comments rules
Always try to explain yourself in code.
Don’t be redundant.
Don’t add obvious noise.
Don’t use closing brace comments.
Don’t comment out code. Just remove.
Use as an explanation of intent or clarification of code.
Use as a warning of consequences.
Use as Legal and Informative comments.
Use as TODO comments.

1. Always try to explain yourself in code
It only takes a few seconds to clear the majority of your thoughts in code. In many cases, it’s all about developing a method that tells the same thing as your statement.
Apparently, many programmers have found it uncommon, if ever, to be a good way to describe code. It’s clearly wrong. What are you going to want to see? The following:
// Check to see if the employee is eligible for full benefits
if ((employee.flags & HOURLY_FLAG) &&
(employee.age > 65))
Or you can avoid comment using a function with descriptive as below:
if (employee.isEligibleForFullBenefits())
Another example:
// student is eligible for blood donation
if (student.age >= 17 && student.weight >= 58.0
&& student.height >= 1.55)
{
scheduleBloodDonatingSessionWith(student);
Maybe in the example above you don’t think the point is bad. It’s not that bad, of course. However, consider the lost chance to obtain a useful method or property:
if (student.isEligibleForBloodDonation)
{
scheduleBloodDonatingSessionWith(student);
"Don’t Use a Comment When You Can Use a Function or a Variable."

2. Don’t be redundant.
You know, saying the same thing over and over again…
You can understand what is happening only by reading the file. This means that making comments is pointless after you have explained yourself.
You no longer need a statement when you have a good name for your field or method explaining the nature of the field or method. For example, when called, a method which is called “SendEmail” needs no further comments. The name of the way an e-mail is sent is obvious.
// if the student is at least 18 years of age
if (student.age> = 18){
// send meeting invitation to the student notificationService.sendMessageTo(student, meetingInvitation);
}
else // if the student is younger than 18 years
{
// sends a meeting invitation to the student’s legal guardian notificationService.sendMessageTo(student.parent,meetingInvitation);
}
3. Don’t add obvious noise
The developers in many cases do not say what they want to do. You may then end up with a message that a customer is sending an e-mail, then eventually debugging and trying to understand why the e-mail is not sent.
Finally, you understand that the way you are named does not submit an e-mail but just creates the email object.
Normally you end up with rules in big companies and projects which require comments from each method and class. You end up with several observations that don’t really add meaning.
As an example:
public void sendMailer(Customer customer)
{
foreach (var address in customer.Addresses) //Cycle through all of the customer's addresses
_mailService.sendGreting(address); //Call the mail service to send a greeting mailer to the address
}
Typically, this kind of thing is fine. People internalize the wisdom to take those that come after them into account and to mistake too much information instead of too little information. But it just becomes meaningless noise at some point.
Programmer maintenance requires context — not lessons in programming. You know what foreach) (does and you know the fundamentals of calling a function. Save some time and some noise with the codebase and don’t try to clarify your feedback on language.
Funny comments that developers using for comments:
i++; //increment iORreturn 1; # returns 1
4. Don’t use closing brace comments.
Often programmers comment on the closing braces. This may be important with long functions and deeply embedded structures, but only for the sort of small and encapsulated features, we select. So if you want your closing braces to be described, try to shorten your functionalities.
} // End of While Block
} // End of if block
} // End of outer if block
} // End of method
“What the error is?! “Is it possible to?” It’s Internet ether that I can see some of your indignations. “That will genuinely help you to grasp the ends of a wide loop!
I’ll admit that if you have massive loops with multiple levels of nested scope, such a statement can also help. In this case, the issue is not the statement itself, but the maintenance nightmare.
Forget regarding these remarks. This problem coding style is normalized and the team gets stubborn. Rather than commenting on the end of the reach, extract methods until the blocks are so wide that you can no longer see where they were initiated.
5. Don’t comment out code. Just remove.

Do not leave the code commented out, please! Please! People would be scared to take it away. You use a version control system, I believe. So delete the commented file. As senior developers, you should not approve these kinds of codes of your junior developers.
"Before you commit, remove all “commented-out” code"
function foo(bar) {
const baz = bar(false)
// we no longer do this for some good reason
// if (baz === 'foobar') {
// return baz
// } else {
// return bar.foobar()
// }
return baz
}
This function should look like this:
function foo(bar) {
return bar(false)
}
6. Use as an explanation of intent or clarification of code
Sometimes you need can feel it is necessary to explain what you tried to do due to some complex algorithm or another reason. However, be sure you are not able to improve the code design.
When expressing intention, a statement is often useful. What we have done in the code is not necessary to comment on, since the reader can display the code itself. What we want to do in the code is more important.
We can’t tell exactly what our goal is in some cases. That is why we must add notes that clarify more and justify why we have not taken a particular action. Perhaps there’s a flaw in a library we had to stop or we had a peculiar request for the client.
7. Use as a warning of consequences.
Often we know that certain code lines are very necessary and that the program, for example, could crash without them. In this situation, other developers might be warned of the value of certain code lines.
A good example is a mutex variable used for access to a common resource. Perhaps not all developers will know the meaning of this mutex and it needs notice.
An example worth more than 1000 words. :)
//
// Dear maintainer:
//
// Once you are done trying to 'optimize' this routine,
// and have realized what a terrible mistake that was,
// please increment the following counter as a warning
// to the next guy:
//
// total_hours_wasted_here = 42
//OR// Magic. Do not touch.OR// I will give you two of my seventy-two virgins if you can fix this.OR// drunk, fix laterOR// I am not sure if we need this, but too scared to delete.
8. Use Legal and Informative comments
There are situations where the legal justification is that you have to make a comment. The code may be interpreted and modified according to particular license conditions. In this case, you can add a comment specifying this, but not all license terms. From the article, you can point to a particular document or URL connection explaining the conditions of the license. With this detail, you don’t want 200 lines of comments.
Often a comment will add value to a file. For example, when we provide more specifics about what a method returns. Beware that there are cases in which the need for return values comments can be omitted by a good name of a process.
Example:
// Copyright (C) 2020 by Someone, Inc. All rights reserved.
// Released under the terms of the GNU General Public License
9. Use as TODO comments
I’m never proposing a TODO comment! If you know that you have something to do, just do that. Please build a ticket and make it available in some way if you can not do it right now. You can use task management tools for that.

Otherwise, TODO is likely to be forgotten.
Example:
// TODO-MdM these are not needed
// We expect this to go away when we do the checkout model
protected VersionInfo makeVersion() throws Exception
{
return null;
}
Often you forget to check the TODOs you added before publishing the file. Therefore, I have needed a long period that emphasizes them and tells me that notes or items have not yet been completed.
There are several extensions for VScode IDE like the below-mentioned ones.Todo Markdown
Markdown Todo
To-Do Tasks
This was my article about using comments in your code. Even though there are some forms of good comments, I think that you should try to minimize the usage of comments in general.
Don’t forget that the simplest rules are the best ones!

Last updated
Was this helpful?