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.
4 Trackbacks
-
May 9th, 2011 / 04:52
-
May 11th, 2011 / 08:41
-
May 13th, 2011 / 21:33
-
February 14th, 2012 / 08:41
23 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.

