One of the first things you learn to do incorrectly as a programmer is commenting your code. My experience with student and recently graduated programmers tells me that college is a really good place to learn really bad code commenting techniques. This is just one of those areas where in-theory and in-practice don’t align well.
There are two factors working against you learning good commenting technique in college.
- Unlike the real world, you do a lot of small one-off projects as a solo developer. There’s no one out there fantasizing about dropping a boulder on you for making them decipher your coding atrocity.
- That commenting style you are emulating from your textbook is only a good practice when the comments are intended for a student learning to program. It is downright annoying to professional programmers.
These tips are primarily intended for upstart programmers who are transitioning into the real world of programming, and hopefully will prevent a few from looking quite so n00bish during their first code review. Code Review? Oh yeah, that’s something else they didn’t teach you in school, but that’s a whole other article, I’ll defer to Jason Cohen on that one.
So let’s get started…
(1) Comments are not subtitles
It’s easy to project your own worldview that code is a foreign language understood only by computers, and that you are doing the reader a service by explaining what each line does in some form of human language. Or perhaps you are doing it for the benefit of that non-programmer manager who will certainly want to read your code (Spoiler: He won’t).
Look, in the not too distant future, you will be able to read code almost as easily as your native language, and everyone else who will even glance at it almost certainly already can. By then you will realize how silly it is to write comments like these:
// Loop through all bananas in the bunch foreach(banana b in bunch) { monkey.eat(b); //make the monkey eat one banana }
You may have been taught to program by first writing pseudo-code comments then writing the real code into that wire-frame. This is a perfectly reasonable approach for a novice programmer. Just be sure to replace the comments with the code, and don’t leave them in there.
Computer: Enemy is matching velocity.
Gwen DeMarco: The enemy is matching velocity!
Sir Alexander Dane: We heard it the first time!
Gwen DeMarco: Gosh, I’m doing it. I’m repeating the darn computer!
Exceptions:
- Code examples used to teach a concept or new programming language.
- Programming languages that aren’t remotely human readable (Assembly, Perl)
(2) Comments are not an art project
This is a bad habit propagated by code samples in programing books and open source copyright notices that are desperate to make you pay attention to them.
/* _ _ _ _ _ _ _ _ _ _ _ _ (c).-.(c) (c).-.(c) (c).-.(c) (c).-.(c) (c).-.(c) (c).-.(c) / ._. \ / ._. \ / ._. \ / ._. \ / ._. \ / ._. \ __\( Y )/__ __\( Y )/__ __\( Y )/__ __\( Y )/__ __\( Y )/__ __\( Y )/__ (_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._) || M || || O || || N || || K || || E || || Y || _.' `-' '._ _.' `-' '._ _.' `-' '._ _.' `-' '._ _.' `-' '._ _.' `-' '._ (.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.) `-' `-' `-' `-' `-' `-' `-' `-' `-' `-' `-' `-' -It's Monkey Business Time! (Version 1.5) */
Why, that’s silly. You’d never do something so silly in your comments.
ORLY? Does this look familiar?
+------------------------------------------------------------+ | Module Name: classMonkey | | Module Purpose: emulate a monkey | | Inputs: Bananas | | Outputs: Grunts | | Throws: Poop | +------------------------------------------------------------+
Programmers love to go “touch up” their code to make it look good when their brain hurts and they want something easy to do for a while. It may be a waste of time, but at least they are wasting it during periods where they wouldn’t be productive anyway.
The trouble is that it creates a time-wasting maintenance tax imposed on anyone working with the code in the future just to keep the pretty little box intact when the text ruins the symmetry of it. Even programmers who hate these header blocks tend to take the time to maintain them because they like consistency and every other method in the project has one.
How much is it bugging you that the right border on that block is misaligned? Yeah. That’s the point.
(3) Header Blocks: Nuisance or Menace?
This one is going to be controversial, but I’m holding my ground. I don’t like blocks of header comments at the top of every file, method or class.
Not in a boat, not with a goat.
Why? Well let me tell you, George McFly…
They are enablers for badly named objects/methods – Of course, header blocks aren’t the cause for badly named identifiers, but they are an easy excuse to not put in the work to come up with meaningful names, an often deceptively difficult task. It provides too much slack to just assume the consumer can just read the “inline documentation” to solve the mystery of what the DoTheMonkeyThing method is all about.
JohnFx’s Commandment:
The consumer of thy code should never have to see its source code to use it, not even the comments.
They never get updated: We all know that methods are supposed to remain short and sweet, but real life gets in the way and before you know it you have a 4K line class and the header block is scrolled off of the screen in the IDE 83% of the time. Out of sight, out of mind, never updated.
The bad news is that they are usually out of date. The good news is that people rarely read them so the opportunity for confusion is mitigated somewhat. Either way, why waste your time on something that is more likely to hurt than help?
JohnFx’s Maxim of Plagiarized Ideas :
Bad Documentation is worse than no documentation.
Exception: Some languages (Java/C#) have tools that can digest specially formatted header block comments into documentation or Intellisense/Autocomplete hints. Still, remember rule (2) and stick to the minimum required by the tool and draw the line at creating any form of ASCII art.
(4) Comments are not source control
This issue is so common that I have to assume that programmers (a) don’t know how to use source control; or (b) don’t trust it.
Archetype 1: “The Historian”
// method name: pityTheFoo (included for the sake of redundancy) // created: Feb 18, 2009 11:33PM // Author: Bob // Revisions: Sue (2/19/2009) - Lengthened monkey's arms // Bob (2/20/2009) - Solved drooling issue void pityTheFoo() { ... }
The programmers involved in the evolution of this method probably checked this code into a source control system designed to track the change history of every file, but decided to clutter up the code anyway. These same programmers more than likely always leave the Check-In Comments box empty on their commits.
I think I hate this type of comment worst of all, because it imposes a duty on other programmers to keep up the tradition of duplicating effort and wasting time maintaining this chaff. I almost always delete this mess from any code I touch without an ounce of guilt. I encourage you to do the same.
Archetype 2: “The Code Hoarder”
void monkeyShines() { if (monkeysOnBed(Jumping).count > max) { monkeysOnBed.breakHead(); // code removed, smoothie shop closed. // leaving it in case a new one opens. // monkeysOnBed.Drink(BananaSmoothie); } }
Another feature of any tool that has any right to call itself a SCM is the ability to recover old versions of code, including the parts you removed. If you want to be triple super extra sure, create a branch to help you with your trust issues.
(5) Comments are a code smell
Comments are little signposts in your code explaining it to future archaeologists that desperately need to understand how 21st century man sorted lists of purchase orders.
Unfortunately, as Donald Norman explained so brilliantly in The Design of Everyday Things, things generally need signs because their affordances have failed. In plain English, when you add a comment you are admitting that you have written code that doesn’t communicate its purpose well.
Despite what your prof told you in college, a high comment to code ratio is not a good thing. I’m not saying to avoid them completely, but if you have a 1-1 or even a 5-1 ratio of LOC to comments, you are probably overdoing it. The need for excessive comments is a good indicator that your code needs refactoring.
Whenever you think, “This code needs a comment” follow that thought with, “How could I modify the code so its purpose is obvious?”
Talk with your code, not your comments.
Technique 1: Use meaningful identifiers and constants (even if they are single use)
// Before // Calculate monkey's arm length // using its height and the magic monkey arm ratio double length = h * 1.845; //magic numbers are EVIL! // After - No comment required double armLength = height * MONKEY_ARM_HEIGHT_RATIO;
Technique 2: Use strongly typed input and output parameters
// Before // input parameter monkeysToFeed: // DataSet with one table containing two columns // MonkeyID (int) the monkey to feed // MonkeyDiet (string) that monkey's diet void feedMonkeys(DataSet monkeysToFeed) { } // After: No comment required void feedMonkeys(Monkeys monkeysToFeed) { }
Technique 3: Extract commented blocks into another method
// Before // Begin: flip the "hairy" bit on monkeys foreach(monkey m in theseMonkeys) { // 5-6 steps to flip bit. } // End: flip the "hairy" bit on monkeys // After No comment required flipHairyBit(theseMonkeys);
As an added bonus, technique 3 will tend to reduce the size of your methods and minimizing the nesting depth (see also “Flattening Arrow Code”) all of which contribute to eliminating the need for commenting the closing tags of blocks like this:
} // ... if see evil } // ... while monkey do. } // ... if monkey see. } // ... class monkey } // ... namespace primate
Acknowledgments
Several of the ideas presented here, and a good deal of the fundamental things I know about programming as part of a team, I learned from the book Code Complete by Steve McConnell. If you are a working programmer and have not read this book yet, stop what you are doing and read it before you write another line of code.
Filed under: How To..., Technology Tips | Tagged: best practices, Commenting Code, programming, tips |
Read, read, read. “Yeah, yeah, yeah!” Read more: “Uh oh…” 😦
Guilty on Archetype 2 and the closing tags of blocks.
That’s funny, I was thinking the same thing. Except I refactor all of the code I want to hoard into framework style classes or extensions – probably just as bad in the end.
Good advice in here. Another must-read that covers the same grounds (among other things) is Robert Martin’s book “Clean Code”.
Thank you for putting up a lot of my commenting styles for public display 😉 I will keep in mind you suggestions going forward. Thanks for sharing…
Great post. Very good point that what we learn in college is entirely the wrong way to comment. I love the link to affordance/signs with respect to comments. Very good connection
[…] Story: 5 Best Practices for Commenting Your Code) codereview, comments codereview, comments 21 Mobile Apps Development Frameworks […]
I once worked on a project where the project manager assured me the code base was quality because it was well commented by previous developers. It wasn’t.
[…] @javahispano: 15 libros gratuitos electrónicos sobre desarrollo con HTML/CSS http://ow.ly/5w60G […]
Hello,
I always wanted to see in eclipse (More information on/after closing bracket):
https://bugs.eclipse.org/bugs/show_bug.cgi?id=256933
Funny stuff!
doh ! the only point of a comment is to make the code easier to support for a future engineer. people should remember ” who is ever going to read this, and who is ever going to care ?” – so only service your future customers, and if there aren’t any then don’t bother with the comment, it will fall amongst trillions of wasted words no one reads !
Yeah, I think this is funny, as I agree. My boss once wanted me to write comments just as much as I wrote code, and I couldn’t see wasting double the time in developing the project, just to fancy his inquisitiveness to want to possibly learn programming by reading my comments to the code – which I suspected was a desire of his. When I said no, his defence was then to say that he would need to pass on my project to somebody who wouldn’t understand how to read the code. Hello? If they can’t read code, then they don’t need to be trying to program the project. Too much comments in the code is either for newbees or dummies!
Great article. I really loved all of your examples. You were very creative in creating such a great read. Has anyone had any real world experience enforcing your selected commenting style (no matter how creative) with static analysis tools? The company that I work for, Parasoft, offers static analysis tools that can be customized to check different commenting styles (http://www.parasoft.com/jsp/capabilities/static_analysis.jsp?itemId=547). I’m curious to see if anyone is actually using (or looking for) such functionality.
“How much is it bugging you that the right border on that block is misaligned? Yeah. That’s the point.”
right click -> inspect element -> delete two spaces -> smile -> continue reading
[…] appears to be broken. Comments in code can be incredibly useful when they’re used in the right way. If you feel the urge to comment in code, it’s important to do so and tell the reader why […]
Why do you title your blog post “5 best practices” and then explain the worst practices? That’s highly misleading…
Perhaps you shouldn’t be writing an article about proper comment etiquette if you don’t yet know what proper comment etiquette is.
The internal documentation you encourage towards the end can only help to document what is happening, but not why (hintedy hint) it is happening. Sometimes you want to tell people why you flip the “hairless” bits, for example, because it may not be obvious.
When you can’t think of a use for a tool, that doesn’t mean the tool is useless. Let me know when you’re more humble to considering that there might be an appropriate task for even the most commonly dismissed tools in programming. Then we can discuss another exception to #3 that could also be added as Technique 4 (or perhaps before Technique 2).
Wonderful article Jonh, Really appreciate your efforts. I tried to fill the gaps in this article …. You might be interested to read and learn further at my blog for the Coding Best Practices which are used in the industry http://techieme.in/category/best-coding-practices/
[…] I recently stumbled over this dandy of a blog related to commenting code, enjoy this gem: https://improvingsoftware.com/2011/06/27/5-best-practices-for-commenting-your-code/ […]
// using it’s height and the magic monkey arm ratio
s/it’s/its/
read: “using it is height…” syntax error?
This commenting article reminds me of one I wrote about 20 years ago. Nice to see the same issues are still with us.
Hmm, “Code Complete” is also about 20 years old. Why do we still need to bring this to people’s attention? That should be what’s IN THE CLASSROOM by now.
I got a deal on apostrophe’s at co’stco and damnit if I’m not going to use ’em all before they ‘spoil!
Wait.. this is titled “the best things to practice,” but outlines things you should NOT do. How do you write good comments? How do you know your comments are good? What does GOOD commenting look like? And don’t tell me I should already know. That’s not good design.
This is ridiculous, all 5 “best practices” are “don’t do this bad practice.”
As you point out comments are pretty pointless when they describe WHAT the code does. But how often have you looked at code (including your own) and though “why did I do it this way?”. IMHO comments should explain WHY you have done something, you will undoubtedly forget – but what the code does is always documented by the code itself.
All programs should be commented in such a manner as to easily describe the purpose of the code and any algorithms used to accomplish the purpose.
[…] found very little about commenting code. I did find an interesting article I need to think about a bit more. The general theme of this article is to write code in such a way […]
Thanks for the valuable posting. I just started my career as a Java develper in a company as a trainee. Comments are really very Important to make code more easy and understandable. Thanks for giving your valuable time in this post.
[…] I also say ‘no’? The one place where you DON’T wanna reduce your writing is the documentation! We learned countless times that comments on code is very important. Write as much and/or as […]
[…] Header-Bereiche oberhalb des Codes mit vielen Informationen erfreuen sich keiner allzu großen Beliebtheit mehr. Versionsgeschichten, Autoreninformationen und Co. sollten nur dann dort vermerkt werden, wenn […]
[…] Header-Bereiche oberhalb des Codes mit vielen Informationen erfreuen sich keiner allzu großen Beliebtheit mehr. Versionsgeschichten, Autoreninformationen und Co. sollten nur dann dort vermerkt werden, wenn […]
Thanks, but you should rename the title to ‘5 Worst Practices for Commenting Your Code’. I read through the whole thing expecting to see how to format the comments only to find out I shouldn’t be adding comments in the first place.
Perhaps so. Maybe a better title would be “5 tips for avoiding the need to use comments. IDE’s hate him!”
There should always be comments in the code so anyone can understand the code. But they should be short and to the point.
Great and funny article.
This article could be titled 5 worst practices and how to avoid them as it highlights what NOT TO DO mostly. Noting down all the advice given here, thank you!
Overview what the code is about. It may be obvious when you write it, but not two years later, so write down when this code is used in the application, why it is used and so on. Like “this code handles the situation where a user fills out a form complaining about returned packages lost in the post”. Answers the question “what the hell is this code for”.
If it isn’t obvious, a high level overview how the code works.
Overview what the code is about. It may be obvious when you write it, but not two years later, so write down when this code is used in the application, why it is used and so on. Like “this code handles the situation where a user fills out a form complaining about returned packages lost in the post”. Answers the question “what the hell is this code for”
Best software and Games Downloads for free and Digital products like Hosting,VPN’s and Niche Ideas
Comments needs to explain code that is unexplainable. But the argument is “Code should be self documenting … blah blah ..”. That is like saying in the 21’st century people should not do bad things. But in reality bad people exist today, bad code exists today and will always exist and more will be created and more of these useless articles will be written. So comments are invaluable.
Are we expecting people who write unreadable code to write good comments? I’d prefer they spend the time on making the code better than the comments. BTW: There is nothing wrong with that name…
I have been coding for more than 35 years. One thing I have learned is that commanting is nearly always an indication of poor code. Dogmatic assertions that “comments are invaluable” say much about the quality of the programmer. Comments are usually out of date, just plain wrong, or pointless. Furthermore, most programmers tend to ignore them anyway – except to express irritation that they take lots of screen space.