Post by Aron / Mai 2nd, 2011

Don’t comment your code!


stackoverflow.com

… 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
//

source

stop(); // Hammertime!

source

// 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.

source

6 Trackbacks

41 Comments

  1. PhilMai 2nd, 2011 / 16:14 / #1549

    I totally agree with aron … buuuuuut :)
    I think a viable scenario where one can heavily rely on comments in one’s code is if you give it to someone who is a total stranger to the project/framework/code and has to be able to build things on top of this code. maybe this is also the time when you start thinking about using ASDocs (or JavaDoc …) – to put all the comments into a documentation for everyone to know what the code is all about.
    but don’t get me wrong – you don’t have to write pages over pages of comments to auto-generate a documentation. keep it short and simple.

    apart from that … stop(); // hammertime

  2. PaulMai 2nd, 2011 / 18:10 / #1550

    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! :)

  3. TobiasMai 2nd, 2011 / 21:20 / #1551

    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!

  4. PhilMai 3rd, 2011 / 16:49 / #1553

    tobias is right saying:

    “I think most important is that in one project only one type of documentation is used.”

    but like in the project mentioned above, it unfortunately was not done.
    when you’re working in bigger projects with 3 people and more you should define things like comments (what/where/how/…) and definitely (as paul said) the style of code or code formatting (use of tabs vs spaces, curly braces on the same line vs next line) to make reading the code for everyone easier.

    thanks for the input guys!
    cheers

  5. reelfernandesMai 4th, 2011 / 03:28 / #1555

    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.

  6. Jim DanbyMai 4th, 2011 / 17:05 / #1556

    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.

  7. Peter PanMai 4th, 2011 / 18:08 / #1557

    @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”?

  8. Msi YerrpMai 4th, 2011 / 21:09 / #1558

    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?”

  9. SergeiMai 4th, 2011 / 23:15 / #1559

     * 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.

  10. RonaldMai 5th, 2011 / 04:07 / #1560

    The last comment, make me laugh… i think he loves his wife so much.. hahah a real family guy :)

  11. Jim DanbyMai 11th, 2011 / 12:48 / #1572

    @Peter Pan – repetition may be OK but this topic is so old hat it’s ridiculous.

  12. Danny TuppenyMai 11th, 2011 / 13:46 / #1573

    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-time

    Using 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.

  13. GennadyMai 11th, 2011 / 20:26 / #1575

    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.

  14. WTFMai 11th, 2011 / 20:46 / #1576

    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.

  15. AronMai 11th, 2011 / 21:55 / #1577

    First off: THANK YOU ALL for your comments!

    After following some links I noticed that everyone seams to use the isAvailable example comment :) I wasn’t aware that it made the big round already.

    RE: “Stop Aron, comments aren’t that bad”
    Of course not. There a many cases where comments make totally sense (some of them are named here). My point was: Don’t write any comments if you don’t now how to actually write then. The difference between “what” and “why” for instance isn’t as obvious as we think for many coders out there. If you’re not sure how comments actually working, just leave it. Thats fine, at least you don’t make things worst.

    RE: “Issue is over-discussed”
    Well, after publishing this post I digged around the interweb a bit and indeed; the topic seams to be a hot one recently. I wasn’t my intention to warm up cold coffee.

  16. AronMai 11th, 2011 / 22:06 / #1578

    @Danny Tuppeny
    Nice read. However the only point I agree with is that comments come into the game when good code is transformed into “hacky” code.

    Even with your example line (ScreenState); if the rest of the program is clean code I would understand the the screen in hidden because it’s needed later. Can I be sure with messy code? No! Can I be sure with clean code? Hell yeah!

    You assume that we write (to be defined) less-then-ideal code. IMHO we’re touching dangerous grounds, if we take that as the default. Let’s write ideal code. And in cases where the code is not-so-ideal, well, lets use comments… :)

  17. AronMai 11th, 2011 / 22:08 / #1579

    @WTF
    Well, sorry for my direct language. Of course this is IMHO. I just tried to give clear guidelines. Feel free to disagree with them.

    Note that I assume clean code for my statements. If you however are in the situation of not working with clean code (remember clean code == clear code), comments are indeed a way to clear things up (you named missing code standards).

    For instance: If you follow the rule that a function / class should do only one thing, your class might not even have that much lines you and you don’t need headers.

  18. Danny TuppenyMai 12th, 2011 / 13:48 / #1580

    @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.

  19. AronMai 12th, 2011 / 15:01 / #1581

    @Danny
    I think the misunderstanding is, that the developer need to understand the complete program in order to make adjustments. The opposite is the case.

    The dev only needs to understand the file / class / function where the relevant action happens. You may ask: How to find this place in code? Good point. But comments wont help you with that either.

    If the program is written in clean code you can be sure that the other parts of the program are just fine. No need to worry about it. No need to be scared of side effects. (again, if the code is not “clean”, comments might help to clear things up)

  20. Danny TuppenyMai 13th, 2011 / 17:59 / #1582

    @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)

  21. Miller MedeirosJuli 29th, 2011 / 21:45 / #1605

    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/

  22. PeteSeptember 13th, 2011 / 11:49 / #1617

    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.

  23. ApparentlyANoobFebruar 9th, 2012 / 12:58 / #1643

    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.

  24. Herman van der BlomMärz 24th, 2012 / 00:26 / #1651

    @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.

  25. bobcMai 6th, 2012 / 20:25 / #1660

    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.

  26. aparnaJanuar 6th, 2013 / 16:16 / #1735

    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.

  27. how to create a blogMärz 3rd, 2013 / 09:43 / #1741

    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!

  28. miumiu 新作April 22nd, 2013 / 00:05 / #1757

    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.

  29. Shopping Web TemplatesApril 22nd, 2013 / 06:02 / #1758

    Reduce! I believe it’s going to be a lot more successful in the event that presented better.

  30. HomerApril 23rd, 2013 / 11:27 / #1759

    Ahaa, its nice dialogue about this post here at this blog, I have
    read all that, so now me also commenting at this place.

  31. ChristoperMai 2nd, 2013 / 22:28 / #1766

    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 ;)

  32. Ebay search toolMai 12th, 2013 / 05:07 / #1772

    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!

  33. http://df-music.blogspot.de/Mai 14th, 2013 / 16:28 / #1778

    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.

  34. http://greencoffeecleanse.netMai 17th, 2013 / 04:22 / #1780

    Your way of describing all in this paragraph is actually good, every one be able to without difficulty understand it, Thanks a lot.

  35. VirgieMai 23rd, 2013 / 13:23 / #1785

    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?

  36. word referenceMai 24th, 2013 / 20:03 / #1786

    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.

  37. essential oilsMai 25th, 2013 / 10:04 / #1787

    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.

  38. NicholMai 26th, 2013 / 01:22 / #1788

    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.

  39. JosephineJuni 1st, 2013 / 09:36 / #1792

    You should take part in a contest for one of the
    finest websites online. I will highly recommend this site!

  40. lakewood housesJuni 5th, 2013 / 02:50 / #1794

    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.

Post a comment