DEV Community

Cover image for Don’t comment your code
Nada Elokaily
Nada Elokaily

Posted on • Updated on

Don’t comment your code

Your First Developer Instinct Is To Disagree But Hear Me Out.

I'm not saying comments are all bad. If used properly comments are very powerful but they aren't the answer to your mess, in fact they might make another mess.
A code could brilliantly solve a critical problem using a well-crafted algorithm, utilizing a famous design pattern or exploiting from a revolutionary feature of a programming language, while depending on providing comments each step of the way and yet be a mystery to the team of developers maintaining it. Why?!
Some developers tend to focus more on writing time-wasting comments than on refactoring the code itself. Here are some comments your team is better off without:

Redundant Comments

Comments should be adding value or describing an original logic, not translating syntax. if the code was well written it won’t need this extra comment to narrate each line’s job.

You can clearly see here that the comment is so uncalled for especially with all the descriptive naming.



 // The processor delay for this component.
 protected int processorDelay = -1;


Enter fullscreen mode Exit fullscreen mode

Misleading Comments

The road to hell is paved with good intentions. The author can put an inaccurate comment for all the right reasons, yet that would cost a poor programmer an expensive debugging session.

For example the method here does not return when this.closed becomes true. It only returns if this.closed is true; otherwise, it waits for a blind time-out and then throws an exception if it is still not closed. The difference is astounding!



// Returns when this.closed is true. Throws an exception on timeout is reached.
public synchronized void waitForClose(final long timeoutMillis) throws Exception
{
    if(!closed){
        wait(timeoutMillis);
        if(!closed)
            throw new Exception("MockResponseSender could not be closed");
    }
}


Enter fullscreen mode Exit fullscreen mode

Mandated Comments

Some mandatory comments might not be that useful afterall. Comments should not be just clutter.

javadocs here are just clutter.



/**
 * @param title The title of the CD
 * @param author The author of the CD
 */
 public void addCD(String title, String author) {
     CD cd = new CD();
     cd.title = title;
     cd.author = author;
     cdList.add(cd);
 }


Enter fullscreen mode Exit fullscreen mode

Noise Comments

Comments should provide new information otherwise they are just noise that we learn to ignore. If you ignore a comment it means that it shouldn’t have been there in the first place.

Not only did this author write an unnecessary comment but he also forgot to add the catch body and left a mumbling comment with no context.



try
{
     // Continue normal flow
     doSomething();
}
catch(Exception e1)
{
     // Give me a break!
}


Enter fullscreen mode Exit fullscreen mode

Function or variable substitution comments

A complex code line doesn't need a comment, what it needs is to be refactored or broken to smaller components.

check this rephrasing, Amazing right?



// does the module from the global list <mod> depend on the
// subsystem we are part of?
if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem())) { }


Enter fullscreen mode Exit fullscreen mode

Rephrasing



ArrayList moduleDependees = smodule.getDependSubsystems();
String ourSubSystem = subSysMod.getSubSystem();
if (moduleDependees.contains(ourSubSystem)) { }

Enter fullscreen mode Exit fullscreen mode




Position Marker Comments

Marking a particular position with a comment is rarely useful; it makes sense to gather certain functions together beneath a banner But I don't see how useful that is for each function, in general they actually may be just clutter.

Admit it you did this ;)



// Actions //////////////////////////////////

Enter fullscreen mode Exit fullscreen mode




Attribution Comments

There is no need to pollute the code with little bylines. There are so many source control tools that are very good at remembering who added what, when

Git blame is after all of us, I feel so exposed..
Alt Text

Commented-out Code

Commented out sections aren't too important to delete, Actually most source code control systems remember the code for us. We don’t need to be hoarding useless pieces of inactive code anymore.

Remember the first time you found out you're clingy?



InputStreamResponse response = new InputStreamResponse();
response.setBody(formatter.getResultStream(), formatter.getByteCount());
// InputStream resultsStream = formatter.getResultStream();
// StreamReader reader = new StreamReader(resultsStream);
// response.setContent(reader.read(formatter.getByteCount()));

Enter fullscreen mode Exit fullscreen mode




Non-local Comments

Comments should describe the code it appears near to. There should be an obvious connection between the code and the comments.

Don’t offer irrelevant or system wide information in the context of a local comment. The place for Interesting historical discussions or irrelevant descriptions of details is not comments.

Important

This article is not an invite to ditch comments. Comments are powerful tools, just use them wisely and invest in their quality, Also never forget that refactoring the code is key.

References

This article is based on Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin, the book is highly recommended to read, such an amazing book that will add a lot to you.

Top comments (70)

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

Mostly good article.

I agree with David, ditch the clickbait title. Your content is worthy of better than that.

Also, handle the book with tongs, hey? It's a mix of good ideas and really bad ideas, packaged so tightly together you have to already be something of an expert to parse between them. Martin is literally the least qualified person to explain Clean Coding in a healthy and constructive manner, and that's considering the fact that he coined the term. I strongly recommend sourcing your insights from someone who doesn't strut like he's the incarnation of Neo.

On the topic of comments, I like to say never send a comment to do a name's job, and never send a name to do a comment's job.

Collapse
 
nadaelokaily profile image
Nada Elokaily

I agree with you, I think it is a general rule of thumb that you shouldn't just take for granted what ever you read in a book no matter how good the book is.
These were the points that I agreed with Robert in this chapter, but no one should blindly follow them all the way.
Take whatever suits your project and makes it easier for your team

Collapse
 
codemouse92 profile image
Jason C. McDonald

The trouble is, you have to know what you're about before you can really "take what suits your project". There are too many young developers who read "Clean Code" on recommendation, see people quoting it like scripture, and then adopt it wholesale as the One True Way...only to walk headlong into the traps of bad practice that are intermingled with the good ideas.

One should always apply common sense, yes, but if a book is such a mixed bag that you have to heavily sift advice as a beginner to avoid taking up antipatterns...find another book. There ARE books that are generally reliable enough, and whose missteps are insignificant enough that you can rectify them with further learning without any major problems. "Clean Code" is not one of those books.

Thread Thread
 
ajxn profile image
Anders Jackson

So, you forgot one thing.

Recommend one or two you consider is Good.

But yes, I do agree with you.

Thread Thread
 
codemouse92 profile image
Jason C. McDonald

Trouble is, I don't have any on hand. I've picked it up from so many places over the years. If I find some specific examples, I'll share.

Collapse
 
rkennela2 profile image
Ryan Kennel 🐶

Least qualified? That is some massive hyperbole. My guess is your opinion is somewhat clouded by your Neo comment (which has some truth to it and made me laugh).

Clean code was thought provoking when it came out and helped a lot of us become better developers.

I would argue that it is now starting to show its age. Languages and IDEs have changed massively since the books release. As such, the usefulness of the book is much less than during its original release.

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

Least qualified, as in, he has a dangerously overfed ego. A preened ego disqualifies even the smartest person from teaching others reliably.

Collapse
 
nickfotopoulos profile image
Nick Fotopoulos

You left out what you SHOULD comment. The rule is simple. Don't explain what the code does, explain what the intentions of the code are. Anyone can tell what the code is doing by looking at it, but it can often be impossible to understand why it's being done just by looking at the code alone.

Collapse
 
ksaaskil profile image
Kimmo Sääskilahti

That's a good advice, I've heard the same principle in the short form "Comment why, not how."

Collapse
 
kevinhickssw profile image
Kevin Hicks

I agree with the "comment why, not how" a lot. I'm actually a big fan of comments and push for developers to leave more, but I focus on the spots where the code can't be simplified anymore and it's still hard to read. Or the reason behind why we are doing it isn't clear.

It's easy to forget the business or technical reason why we had to do something and then not be able to find the ticket a year later explaining it.

Thread Thread
 
aarone4 profile image
Aaron Reese

Especially with the cadence that language and frameworks are updated today. The more efficient techniques may not have been available when the code was written. I personally have left a whole bunch of notes at the top of a Vue project explaining why I didn't use separate component files and modules (inexperienced dev team, no source code control implementation on site, no experience of setting up build pipelines etc.)

Collapse
 
nadaelokaily profile image
Nada Elokaily

Yeah, I couldn't agree more 😅

Collapse
 
adam_b profile image
Adam Braimah

Absolutely. For all the modern proclamations of "self-documenting" code, code can only show what it's doing, not why. Comments are still invaluable for explaining why something is happening, and sometimes, why it hasn't been done a different way (one which might have face validity, but be wrong).

Collapse
 
nadaelokaily profile image
Nada Elokaily

I might add a new article about which comments to write but this was off the topic I wanted to discuss here,
However, the idea that comments should be adding value or describing an original logic, not translate syntax is mainly what most good comments are about, right?

Collapse
 
rkennela2 profile image
Ryan Kennel 🐶

Great article. This an often overlooked but important topic.

I look forward to the follow up - “Don’t get rid of all comments”

Collapse
 
tobiastimm profile image
Tobias Timm

THIS! Comments for intentions and not repeating what the code is doing

Collapse
 
joaomcteixeira profile image
João M.C. Teixeira

100% agree

Collapse
 
davidhmartin profile image
David Martin

I love the article, but hate the title.
Too many people read these comments-considered-harmful types of articles and mistakenly believe that all comments are bad, which is definitely not the case. In my career I've been annoyed by under-commented code more often than by over-commented.
Having said that, I pretty much agree with everything you said (apart from the title) and I found it quite well written.
The example you give under "Noise Comments" is interesting. It's a common coding standard in Java to generally avoid empty catch blocks, and, in cases where an empty catch block is justified, to include a comment in the block explaining why. If that's a real-world example, I'm guessing that the build system included a checkstyle plugin which enforced that rule, and that the "Give me a break" comment is there to circumvent it. If so, I think that developer's problems go beyond just poor commenting skills! :-)

Collapse
 
nadaelokaily profile image
Nada Elokaily

Well as they say don't judge a book by its cover 😅
If someone got through the first passage thinking that they should not be commenting their code at all they missed the point completely, we both agree that we always should try to write better code with less noise and more valuable comments to make fellow programmers' life easier in the future

Collapse
 
kevinhickssw profile image
Kevin Hicks

I agree that this is a great article, but also agree with David about the title. Unfortunately most people don't actually fully read an article and they will miss the point in the beginning.

I've had many devs share articles like this with me for a reason to not write comments and didn't realize the first paragraph was saying that some comments are good anyways. They only read the subheadings really.

I saw in another comment that you might write another article about which comments to write and I would highly recommend doing that.

It could also be good to include that some times some of the comments you mentioned here as bad could be good. For example mandated comments are good for public packages, APIs, build and code style / generation tools, etc.

Thread Thread
 
ajxn profile image
Anders Jackson

I was also arguing that Java doc in public packages, like Java official documentation is Good and needed.
Even better if some example and useage is in the documentation.

In internal methods, classes only for internal use, not so much.

Collapse
 
vitormalencar profile image
Vitor Alencar

Really nice article =)

Some times we need to comment on the code to also help some co-workers,
it happens to me so many times when I can't fully refactor some piece of code because some other part of the system ( that I usually don't have full control) would depend on it, on that cases I find it helpful to comment on the code and try to bring awareness on of the problem on the code review.

Collapse
 
nadaelokaily profile image
Nada Elokaily

Yes, you should always keep other people maintaining your code in mind, always refactor your code and write better helpful comments to help them understand the logic fast, just don't waste their time with in valuable documentation

Collapse
 
kaitlyn_mccormick_23b1714 profile image
Kaitlyn McCormick

I agree with Vitor. In some businesses, there are those who access the same code to determine a root cause of an issue and correct it. Sometimes, there are junior engineers who find the complex structure intimidating. I still stand by explain the why, not the how. Yet, in some cases, the complex structure if accessed by another team for the same purposes can make a big difference.

Collapse
 
seriousfun01 profile image
SeriousFun01

1) I don't understand this code because it has too many crappy comments that are just noise
2) I don't understand this code because it has no comments

Now which of 1) or 2) is the most likely complaint?

Collapse
 
nadaelokaily profile image
Nada Elokaily • Edited

"I don't understand this code because all the comments are crappy" is the worst which is the case that I mean in this article,
I don't mean that developers shouldn't comment their code at all, I think they shouldn't write bad comments and invest in writing better comments and increase code quality

Collapse
 
seriousfun01 profile image
SeriousFun01

yes, I got your point and I agree :-), but I think if you pick a random piece of code most likely you find it has no comments at all.

Collapse
 
gabrieltoma profile image
Gabriel Toma

I agree with most of your thoughts about commenting, it is indeed a pretty good article. However, I disagree with some of your ideas and I tend to believe some comments are actually helping devs, especially junior devs.

Have you considered your development progress as a junior by reading some code comments? I found they put a lot of value when the code comments are explicit about every step the method they inspect is doing, because they met this type of code through so many tutorials where they comment after each step and telling them what exactly the next line of code is doing.

For mid to senior devs, yes, the comments are not that useful except they provide some good value (like you said). But for juniors, comments might be gold lines!

Just my 2 cents ✌

Collapse
 
coolscratcher profile image
CoolScratcher

A lot of this doesn't apply to block-based programming like Scratch and Snap, I might write a similar article about those two crediting you for the idea. But this certainly is useful for HTML or JS. Props!

Collapse
 
nadaelokaily profile image
Nada Elokaily

Please mention me when you do, I'd love to read that!

Collapse
 
coolscratcher profile image
CoolScratcher

Certainly!

Collapse
 
eelstork profile image
Tea

I don't see this article as having a click-bait title. Once all un-wanted comments are removed, there is almost nothing left.
Only place where I leave comments is (1) where truly hard to understand code can't be replaced by something clearer; (2) marking a transitional, probably undesired code state that for production / workflow reasons can't be fixed right away.

Collapse
 
garrick profile image
Garrick West

I think your argument doesn't go far enough. I'll double down on an your extreme perspective on comments: they're just a code smell. If the code is easy enough to understand, you don't need them. If you need them, then that means you're code is too complicated to stand on it's own (a dangerous situation). If you want to argue that you need "documentation" on your code, great: WRITE A UNIT TEST! Unit test when well written, can't 'lie' like comment can (e.g. get out of date - the tests will break) :) If given a choice between writing comments and writing unit tests, write unit tests!

Collapse
 
stereobooster profile image
stereobooster
Collapse
 
nadaelokaily profile image
Nada Elokaily

Great article!

Collapse
 
donginging profile image
Holly.Z

That is true

Thread Thread
 
donginging profile image
Holly.Z

oh...

Thread Thread
 
donginging profile image
Holly.Z

jeez

Thread Thread
 
donginging profile image
Holly.Z

strenge

Some comments may only be visible to logged-in visitors. Sign in to view all comments.