While there is a lot of article pro and cons that we should comment or not our code, it came to my attention that this is required in programming industry as it’s one of a question I received during job interviews when it comes to Code Practices.
You may not agree with the fact that we should comment on our code, as for some this is extreme by saying that is a sign of bad code. The other extreme is commenting on the code in an exaggerating way.
As a junior, I like to comment on my code as I usually reuse it, and it’s for later information.
Currently, I have a very simple method, that perhaps if you are like me, you’ll find it useful. I am going to break it into three parts:
- to the point.
Every time I comment on code I am keeping it relevant. A long code should be turned into documentation rather than to be considered a tool in the toolbox. So, I am writing a piece of self-explanatory information. This for me in time turned to be a way of remembering why I added the code, which brings me to the next point.
Commenting code is something that should be brief. Of course, I haven’t seen senior developers commenting on their code while recording a tutorial, but that tutorial is giving you some fundamentals that later on should apply, not a real-life example. So, the comment should also be brief. I use at the most two lines with a maximum of 10 words.
Comments to the point.
Comments should always be about “why” I wrote the comment. Lemme explain with a real example: I had to change a “back-to-top arrow” in one of my client’s pages by adding some CSS. While the colors on the website at a certain point were covering the back to the top option I changed the colors and gave it a shadow at the bottom. I wrote a comment that was saying “back-to-top background change”. After one month I needed to make a change on another website and I reused the exact code making some small changes. This is a simple example but when it comes to finding a workaround and the code itself is not explanatory, we really need to comment.
While there’s still debate on commenting or not the code we should always look to be productive not only for the moment but as well thinking in terms of “production” in the future. I understand that commenting code has a bad reputation but we shouldn’t allow dogma to guide our work and our productivity. Commenting my code is a great tool that will help juniors in trouble time. It shouldn’t be abused and working in a team it’s helpful.
Some of my practices
I avoid long comments, I prefer writing documentation.
I avoid in-line comments, I use them only if necessary.
I avoid placing warnings in comments, I do it only to show what I tried and it didn’t work.
Hopefully, this was helpful for you. Until next time have fun coding.