Don’t comment your code!
… unless you know what you do.
The problem
Since I started programming I have always been fighting with “strange” code comments. Everyone told me I had to document my code. Also I wanted to be a good citizen and make it as easy as possible for my co-workers to understand my code. On the other hand there was always so little time. And writing good comments takes time. Also I understood that when the codes changes I also have to update the comments (even more time consuming). Plus I was not sure what to comment. Every line? Every method? Or a summary of the class in the header?
When I got better at coding I noticed that no one is writing comments. At least not many. However I found out that comments can be very useful when there is a codeline that needs clarification. So I still felt guilty for not commenting my code.
Last year I got my hands on Clean Code by Robert C. Martin. Dear programmers out there, you need to read this book.
The chapter on Code Comments made me totally change my mind about writing comments and feeling guilty for not writing them. Bottom line: The code itself is the best comment, only write comments when it’s really needed, don’t leave commented code lines.
Example 1 – Annoying
Recently I came into a project with some other programmers. I found the following comment styles (different coding styles aside, that is another story). Which do you find best?
public class AbstractModuleMediator extends Mediator implements IMediator {
/* public variables and consts */
/* protected and private variables and consts */
private static const log : Logger = LogContext.getLogger(AbstractModuleMediator);
/* public functions */
/**
* Constructor for the AbstractModuleMediator class
*/
public function AbstractModuleMediator(name : String, viewComponent : IModule) {
super(name, viewComponent);
}
}
public class SomeModule extends AbstractInteractionModule {
private static const log : Logger = LogContext.getLogger(SomeModule);
// ✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖
// VARIABLES
// ✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖
private var _vo : SomeVo;
// ✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖
// CONSTRUCTOR
// ✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖
public function SomeModule() : void {
};
// ✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖
// PUBLIC FUNCTIONS
// ✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖✖
override public function create() : void {
}
}
public class SomeMediator extends AbstractModuleMediator implements IMediator {
// _____________________________________________________________________________________________________________
// C O N S T A N T
// =============================================================================================================
public static const NAME : String = "SomeMediator/";
private static const log : Logger = LogContext.getLogger(SomeMediator);
// _____________________________________________________________________________________________________________
// V A R I A B L E S
// =============================================================================================================
// _____________________________________________________________________________________________________________
// I N I T I A L I Z E
// =============================================================================================================
public function SomeMediator(name : String, module : IModule) {
super(name, module);
log.debug("VideoPlayerMediator()");
}
// _____________________________________________________________________________________________________________
// P R I V A T E - F U N C T I O N S
// =============================================================================================================
}
public class SomeMediator extends AbstractModuleMediator
{
public static const NAME:String = "SomeMediator/";
private static const log:Logger = LogContext.getLogger(SomeMediator);
public function SomeMediator(viewComponent : IModule)
{
super(NAME, viewComponent);
}
override public function onRegister() : void
{
}
}
So what’s the best commented code? It’s #4. Why? Think about when you first enter a class to make some adjustments. You need to understand the code. You need to read the code. Everything thats distracts you from reading code is useless and should be avoided.
We all know (at least we should) the order of static field, public field, private field, constructor, public methods, private methods. No need to repeat that.
Example 2 – Bad
The other thing Martin points out is the danger of uncommented code lines. This one is harder to achieve since it needs you to make a quick code review on all edited classes before you commit something. Take this example:
facade.registerProxy(new ChannelProxy()); facade.registerProxy(new SoundProxy()); //facade.registerProxy(new SoundAssetProxy()); facade.registerProxy(new SubtitleStateProxy()); facade.registerProxy(new SocialShareProxy()); facade.registerProxy(new TrackProxy());
I had a ticket where I needed to fix a sound issue. I came across this command and the uncommented line left nothing but questions for me. Is this work in progress? Or a permanent removal? Does this Proxy even exist any longer? And most importantly: Does this has something to do with my issue?
Of course someone just forgot to remove this line/comment. However, it cost me some minutes to figure that out.
Example 3 – EVIL
/**
* Always returns true.
*/
public boolean isAvailable() {
return false;
}
Do I need to say more? This – of course – is the worst thing that can happen with code comments. The code changes but the comment stays the same. When you change a commented line/function/method and you can – for whatever reason – not change the comment, delete the comment.
Conclusion
As you see from the examples it’s way harder to write good comments then no comments at all. So instead of making it all worse just don’t do it. If you consider yourself as someone who writes exceptable code, that should explain enough for you and your co-workers.
Thats all folks. Oh wait…
// // 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 = 39 //
stop(); // Hammertime!
// I dedicate all this code, all my work, to my wife, Darlene, who will // have to support me and our three children and the dog once it gets // released into the public.
6 Trackbacks
-
Mai 9th, 2011 / 04:52
-
Mai 11th, 2011 / 08:41
-
Mai 13th, 2011 / 21:33
-
Februar 14th, 2012 / 08:41
-
Juni 13th, 2012 / 18:42
-
November 21st, 2012 / 17:13
41 Comments
-
Nice post, more folks need to be talking about comments.
More important than comments is the code formatting, legibility, and clarity. The code should basically self document. My code tends to be on the verbose side because I prefer to name things as they are. I can’t stand abbreviated names that are not immediately obvious. I always grimace when I see the big section header style comments. And, commented code like the sound example you mentioned is definitely dangerous. Either remove it entirely (preferred) or document why it’s commented.
That said, I don’t agree with “Don’t comment your code”. I think comments have their place. Instead I would say, if you’re going to write comments, think about why they are there and make sure they are worthwhile, specifically, JavaDoc/ASDoc style comments. If you’re writing a library and you need to generate documentation, write comments. If you’re working on code that is shared across multiple projects, write comments. Most development tools these days support some kind of documentation display, based on the comments, that shows up as you’re writing code. This can be super useful and avoids the need to dig into the code you’re working with to understand what it does.
One parting thought….
stop(); // hammertime
…should be encouraged! :)
-
I totally agree to everyone of you in parts. I can say, that i know the project in Detail :)
Example 1 was done by me :) Of course Aron only posted small parts. I think there are parts which are better documented than this.The Part i do totally not agree with is that everyone knows the order of public, protected and private. At first there is not really a order you have to maintain. Important is that everyone in the team of one projects knows about it! And i think you can achieve this by keeping this in mind of your developing by putting one line into the code (note that in example 1 only one star was used – so it will not be visible in your ASDoc)
I think most important is that in one projekt only one type of documentation is used.
Commenting a inherhited PureMVC Mediator does not make sense over all, especially if you do not inherit the documentation as well (And yes! example 1 was done by me/my fdt template ;) )Parts which have always be commented:
- the core functionality (framework etc.)
- difficult and complex structures (e.g. parts which are using realtime 3D calculations like the project aron got the snippets from)I think the best solution is to use the ASDoc standard. I think everyone who is doing ActionScript programming should know the basics of ASDoc. So this knowledge should be a good base for making one consistent documentation.
@Aron: perhaps you find a example of your code without documentation and show how to make it better? I think that would be very interesting.
And at least: Commenting is philosophy… i think 10 developers: 10 philosophies. If we do not name our variables and functions “foo” and “bar” we are one the good side of the force :)
Greets!
-
I agree, comments are only for when you can’t express the intent & purpose through variable/fuction names, and line placement. If your code is consistently needing comments, you might be organizing your classes, and functions poorly. My .02
Thanks for the book recommendation, I’ve been considering it for years now.
-
Do we really need to have this argument reiterated so often? There must have been a hundred duplicates on DZone in the last year alone. Always they are polarised – either “comments are evil” or “comment haters are morons”.
Comments are like de-odorant. Underused = bad, overused = bad.
-
@Jim Danby
Do we really need to say anything after it’s already been said before? Should there be a law, “Something May Only Be Said 100 Times Per Year”?
-
I am always in the situation of debating with myself whether I should comment because my coworker can’t read code. If he doesn’t understand what the code does or he doesn’t know a specific knowledge, he would complain that there are no comments. That always puts us in a situation where I think there are no comments needed and he thinks I am a sloppy developer. In my perspective, the software we do here is very simple and most of the time, writing or reading comments is just a pain. For instance, int a = (b > 0)?1:4; //if b is greater than 0, use 1 otherwise 4.
I don’t think we should put comments on this. So the question is that “for whom the comments are written?” , “To those who don’t know the software at all?” or “To those who has certain knowledge of the software?” -
* Always returns true. is a javadoc not a comment. And it makes sense to write it, because the code isn’t always available for the javadoc users.
-
The last comment, make me laugh… i think he loves his wife so much.. hahah a real family guy :)
-
@Peter Pan – repetition may be OK but this topic is so old hat it’s ridiculous.
-
I posted a similar article on my blog recently:
Writing Comments in Code is *NOT* a Waste of Time
http://blog.dantup.com/2011/03/writing-comments-in-code-is-not-a-waste-of-timeUsing other peoples crap comments is a *poor* excuse not to comment your code. There are many examples of well commented code where the comments add a *ton* of value and would be absolutely stupid to rewrite the code to avoid the comments.
Stop being lazy. Write comments to explain code where it’s not trivially obvious. The next programmer that has to maintain your code might not be as “good” as you, and reading English comments is always easier than parsing code in your head.
-
I usually write a comment when I feel that I need to explain “why”, and not “what”. E.g. WHY I choose this approach here, or WHY we’re using this specific value/object/parameter here etc.
And of course I’m using “xml” comments to document business objects, base functionality, frameworks etc. It’s just convenient – Visual Studio intellysese supports them.
-
Aron, You seem to feel that you are qualified, no required, to tell us all the evils of commenting code. Not everyone is as brilliant as you, people change the order of things, write too much code into a class, and actually are sometimes just bad coders. Comments can do more then parrot the code, and indeed should.
Comments should be used to provide a dialect of understanding what the code is doing, not how it is doing it( that’s the codes job ). Blocking out headers that indicate where things are at a high level makes navigating code MUCH easier. Especially when you have an organization with limited enforcement of the code standards. I always appreciate a point of view, but something so strong as “you should never” always makes me defensive.
-
@Aron Why should you have to read the rest of my program to know what/what that line does?!
I’d rather spend 5 seconds putting a comment on my code than have the next developer spend an hour reading my entire program to understand what a single line does.
In fact, what’s more likely to happen is the developer won’t read the program, he’ll just change it (because there’s no comment advising against it), and then waste a load of time figuring out the bug he’s introduced.
-
@Aron I was referring to your comment about my comment on the ScreenState code not being required. I disagree. The comment makes it quite obvious why the code doesn’t remove the screen. Without the comment, a developer might spend time trying to figure out why it’s not being removed, but hidden (let’s say they’ve investigating why it isn’t being GC’d after the level unloads).
People seem to use bad comments as an excuse to not write comments, or as “evidence” that commenting is bad. It’s quite simple – bad comments are bad, and comments that add something are good. And if you’re deliberately rewriting your code to avoid writing comments (which was suggested in the comments to my post), you’re doing it wrong :o)
-
all good points and the book Clean Code is definitely a “must read”… I agree that we should avoid comments on most cases but also think that some things should always have comments: http://blog.millermedeiros.com/2010/07/always-comment-weird-things/
-
Comments frequently become out of date with the code they are supposed to be documenting.
If you practice TDD, your tests will provide all the documentation a developer needs to understand the code. -
I know my comment is extremely late (given the post date), but had been thinking the same thing recently (comments in codes and can you under/overuse them) and was looking for an article on the subject.
I write perl scripts for a living (well, sort of) and sometimes the scripts I write always end up rather esoteric (due to me still being a fresh out of uni graduate programmer and also due to the nature of the task they’re supposed to do) and after reading this, frankly I feel it’d be a disaster to so scantily comment a code somebody else is supposed to maintain. Like perl scripts, as I’ve come across a lot of opinions describing perl (and its syntax) as ‘pure noise’.
For a start, variables definitely need to have an accompanying code that clarifies what their role in the code is (and no, the var name itself is not as descriptive as a comment, unless you’re into ridiculously long var names).
I often have to maintain other people’s code and it’s taken me sometimes hours to figure out what were they trying to do and especially what a scarcely used variable does that has a name like ‘$temp_var_2″ in some complex, strange looking algorithm, just because they felt comments are a drag (and dare I suggest that the reason why there are no comments is because they felt that the code was good enough on its own).
For me, it’s a matter of elitism and unhelpfulness to think that people reading your code should figure stuff out completely on their own, because it’s ‘clean’. How do you determine clean code objectively? What if somebody less experienced than you is supposed to look after your creation? Wouldn’t a little bit of descriptive code be of great use for everybody be they newbies or pros?
Therefore, let me just say that I’d rather have a commented code (even if over-done) any day of the week than one where the author thought everything is clear enough and there shouldn’t be anything else ‘distracting’ you from reading the code.
-
@ApparentlyANoob, you are absolutely right. Every professional programmer knows it. The best technique is to comment before you write your class or function or whatever. The given example is bad. It only has some lines of code in it. In reality programmers dont comment. You know why? they cant ! They are good in math but a lot of them not in language, the so-called nerdy types. So they are not able to formulate a small comment line. Thats the difficult part to tell in one line what it does in plain English (I am dutch so in my case in Dutch). I cant convince my collegues of the need of it so I see a lot of bad code, bad variable naming, bad function naming. Once somebody asked Bill gates: “do you need to be good in math to be a good programmer” the answer took some time, but then the answer was: “No”. If a programming language was entirely based on math then it was not called a language. So the problem lies in the fact that a lot of programmers need an upgrade course English to write good comments.
-
Well, I take objection to the moralising about whether coders are lazy and selfish. I can easily turn that round and say people who rely on others to explain code to them are also lazy and selfish. I expect competent coders to understand code without relying on comments, it is a standard interview question.
Putting morals aside, the practical issue is that comments are often unhelpful and/or wrong, so I can never rely on the comments. Saying “write good comments” is like saying “write correct code”. Neither happen. The comments never get tested, but the code does. I end up having to fix the bug, and then fix the comment.
Comments are usually just more work, so if you are writing comments on my behalf, I would say please don’t bother.
-
I agree with you.For trivial codes we do not need to write comment.
Most often code will be updated but comments don’t.Recently,I have not commented for the namespace i.e.using System.Collections for one defect fix and I got a code review finding for that saying comment should be added since I added that reference.For me explaining the functionality is more important than commenting every where.
-
When I originally commented I clicked the “Notify me when new comments are added”
checkbox and now each time a comment is added I get four
e-mails with the same comment. Is there any way you can remove people from that service?
Cheers! -
With the season’s emphasis on glitz and shimmer this season, the Chloe Paddington in silver or gold offers just enough glimmer to catch t the trend. We have a diddly along major, twin manages, and also mass media man fastenings in the attributes.
-
Reduce! I believe it’s going to be a lot more successful in the event that presented better.
-
Ahaa, its nice dialogue about this post here at this blog, I have
read all that, so now me also commenting at this place. -
I would like to thank you for the efforts you have put in writing this website.
I really hope to see the same high-grade content by you in the
future as well. In fact, your creative writing abilities has motivated
me to get my own, personal site now ;) -
I do not even know how I finished up here,
but I believed this post was once good. I do not realize who
you are but certainly you are going to a well-known blogger if you
happen to are not already. Cheers! -
Every weekend i used to pay a quick visit this site, because i wish for enjoyment, since
this this website conations in fact nice funny stuff too. -
Your way of describing all in this paragraph is actually good, every one be able to without difficulty understand it, Thanks a lot.
-
Thank you, I have recently been looking for
info about this subject for ages and yours is
the greatest I’ve came upon so far. However, what in regards to the bottom line? Are you sure concerning the supply? -
Excellent goods from you, man. I’ve understand your stuff previous to and you are just extremely fantastic. I really like what you’ve acquired here, really
like what you are saying and the way in which you say it.
You make it entertaining and you still take care
of to keep it wise. I can not wait to read
much more from you. This is really a great site. -
The device is also very light, weighing slightly less than 3 oz.
Some people will rely on transferring data between flash drives and their home computers, or sending
what they wish to have printed to a proxy, such as Fed – Ex.
Make sure you get a decent resolution LCD with any camera in this category. -
Generally I do not learn post on blogs, but I wish to say that this write-up very compelled me to take a look at and do so!
Your writing style has been surprised me.
Thank you, very nice article. -
You should take part in a contest for one of the
finest websites online. I will highly recommend this site! -
Fantastic goods from you, man. I’ve take note your stuff prior to and you’re simply
too wonderful. I actually like what you have received right here, certainly
like what you are saying and the way in which during which
you assert it. You make it entertaining and you still care for to stay it sensible.
I can’t wait to read much more from you. This is really a great web site.
