How To Write Code Comments Well

UPDATE: Due to some overwhelming misunderstandings, I’d like to clarify a few things. I’m not against PHPDoc, or Docblock commenting. Nor am I against the no-comment practices. I believe in good coding practices, and good documentation. The main point of this article is if you DO comment, make those comments useful and not just some throw away stuff that will be compiled into docs later. Seriously. I look through thousands of lines of code a day and Laravel saved me a bunch of headaches by the comments listed below. Not because those comments told me 100% what to do, but because of their headlines that allowed me to scan documents fast and locate important parts of it via Sublime Text’s code map tool. 

I’m caught here in a cross fire of fundamentalist non-commenters (“Your code should describe itself! Comments are evil!”) and fundamentalist commenters (“Use Docblock! Anything else is against standards and thus useless!”) yet people didn’t get my point. I don’t use comments for formal compiled documentation. Nor do I use comments to untangle my mess of code. Just saying!

Code organization is a huge thing, especially for developers (because they deal with code), and often times it’s a philosophical debate as to how code should be documented, if spaces should be used instead of tabs, what kind of documentation should be used and so on.

Yet, what no one brings up is the dire issue of COMMENTING. We can all agree that comments are essential (and sometimes used to build half-ass documentation on big systems) but what no one really mentions is the fact that people are crappy commenters. From syntax use to descriptions. We just suck, really badly and that’s not the way a Zen Developer should be. Senor Dan Eden touched on this when discussing max.css conventions.

There are a few things you can do to REALLY improve your commenting, to the point where I’ll fall in love with your damn code, will want to fork, rebase it, make it my own, just to have such a great commenting system.

Not only will this be super-damn-awesome but it will be useful, very useful, especially when working on big projects where organization and understanding is key. Like I said, it’s what makes a good web developer.

Having worked with Laravel for the past couple of weeks, I think I found a contender. So here’s how YOU can make your commenting attractive, desirable, and make it feel young and vibrant.

Step 1. Be informative

Like seriously. I had to, in the past, go back and comment someone else’s code (no, not a newb dev, a seasoned ‘pro’) just for it to make sense. If I EVER see this again, I’m going to do something stupid and something very bad (like write this post or an equivalent again):

/* another section */
/* var something <- integer
 var whateverelse <- string
function(int, string)

*/

No really, that’s commenting? Thanks for letting me know something and whateverelse need to be an integer and string and that the function needs int and string. Genius. How about telling me what this code does and what the something and whateverelse are supposed to be? How about telling me where this is used and what to do about?

Here’s a slight improvement (meant for code documentation)

/* Media Section
@something = A variable used to number stuff
@whateverelse = A var describing said stuff
@function(int,string) = needs something and whatever else

*/

Better. A bit more useful. Let’s crank it up a bit and see how I comment stuff:

/* MEDIA SECTION
something = variable used to number stuff (number of users, number of links etc.) REQUIRED
whateverelse = string to describe said stuff such as "Number of Users", "Number of Links". NOT REQUIRED (defaults "Number of stuff")
function() = takes in 'something' and 'whateverelse', outputs a neat HTML thing. Does not need to be escaped
*/

Let’s add a bit of formatting and better semantics:

/*
MEDIA SECTION

something:
* int
* numbers stuff
* ex: number of users, number of links
* REQUIRED for function()
* no default

whateverelse:
* string
* describes 'something'
* ex. "Number of Users", "Number of Links"
* NOT REQUIRED for function()
* default: "Number of Stuff"

function(int, string)
* uses 'something' and 'whateverelse'
* outputs a neat HTML thing
* ex: <span>4</span> of Number of Links
* no need for escaping

*/

Whoa, holy crap! That’s like a tutorial right there! It all makes sense now. You can minimize the crap out of that javascript right there as long as you leave me THIS kind of documentation!

Let’s look at what  Laravel does:

/*
|--------------------------------------------------------------------------
| Application 404 & 500 Error Handlers
|--------------------------------------------------------------------------
|
| To centralize and simplify 404 handling, Laravel uses an awesome event
| system to retrieve the response. Feel free to modify this function to
| your tastes and the needs of your application.
|
| Similarly, we use an event to handle the display of 500 level errors
| within the application. These errors are fired when there is an
| uncaught exception thrown in the application.
|
*/

Event::listen('404', function()
{
	return Response::error('404');
});

Their entire framework has a big novel written in it. I know it adds to space but REALLY! Look at this. No, not each line is commented like this but a good amount of the framework is, especially the part a regular developer will deal with (the application config). It really is like a novel, a well written novel that you’re eager to read. I wish more software products were done like this.

Step 2. Formatting

In the previous examples, you can see that FORMATTING has a lot to do with comments too. And that’s what got me start on my article. I LOVE comment separators. I absolutely love them. When you have a big chunk of ASCII that lets you know “HEY, hey, dude, new section. Pay attention to this!”

There are several alternatives and I think, again, Laravel has nailed it. Let’s look at standard commenting conventions:

// Comment Title
/* Comment Block Text
that spans several lines
*/

So this is actually pretty good but we’ll kick it up a notch by challenging Twitter’s Bootstrap’s commenting:

// CSS3 PROPERTIES
// --------------------------------------------------.

// IE7 likes to collapse whitespace on either side of the inline-block elements.
// Ems because we're attempting to match the width of a space character. Left
// version is for form buttons, which typically come after other elements, and
// right version is for icons, which come before. Applying both is ok, but it will
// mean that space between those elements will be .6em (~2 space characters) in IE7,
// instead of the 1 space in other browsers.

That’s a heading, and that’s a multi-line. How much prettier is that? Not too much extra work (if you’re working in an IDE or Sublime Text at least), you just CTRL+/ or CTRL+K+C it and you’re good to go ;) So, I would appreciate this kind of commenting at the minimum. For coding, include wtf all those things are that you’re using. Thanks!

The thing is, I’m not a hundred percent fan of this. The title does not SEPARATE enough, it’s easy to get lost in. Bootstrap also varies the length of the lines underneath. Not cool.

Let’s kick it up a notch, have you seen this type of commenting?

/******************
***** TITLE ********
******************/

/*********************************
Multiline Stuff Goes here!

*********************************/

As patriotic as this may seem, it’s killing my eyes. Stop it. On top of that, if you change the title name, you deal with hazardous formatting. Here’s my IDEAL:

/*
|--------------------------------------------------------------------------
| Laravel Configuration Loader
|--------------------------------------------------------------------------
|
| The Laravel configuration loader is responsible for returning an array
| of configuration options for a given bundle and file. By default, we
| use the files provided with Laravel; however, you are free to use
| your own storage mechanism for configuration arrays.
|
*/

LaravelEvent::listen(LaravelConfig::loader, function($bundle, $file)
{
	return LaravelConfig::file($bundle, $file);
});

Why Laravel again? Here’s why:

  • the block title comment does NOT need any special reformatting with a different tile (many comment titles do)
  • the description is latched onto the tile and paragraphed with enough space to increase legibility
  • it’s easy to copy/paste it and to add more lines
  • when scanning through the site, these headings REALLY help separate different sections

SO that’s it, that’s what my beef is today.

I hope everyone appreciates this strange rant on comments!

What I (Selfishly) Expect The Internet People To Do

Make a Sublime Text 2 plugin that will automatically create a a small comments template akin to Laravel’s (which someone informed me exists). Press CTRL+A+C (Control + Awesome + Comment) and bam, you got that neat little structure.

Next, I want someone to create a documentation creating tool that supports markdown and that little sweet commenting structure.

I also expect people to get angry, and virally boom with their anger for developers that don’t comment well and for management that pushes developers not to spend their time commenting!

Comments

  1. timw4mail says:

    What, no docblock? So those wonderful comments have to be custom-parsed for reference documentation?

    • oh, I’ve never used it and when I checked it out, I didn’t really like the way the comments look but I saw that the Sublime Text 2 plugin for docblock allows for customization :)

      • richardathome says:

        But now you’re expecting everyone to follow your guidelines as opposed to the pretty much industry standard DocBlock which also has the benefit of being machine readable…

        Your argument as to not liking the way the comments ‘look’ could easily be used to your own commenting style too for another developer not familiar with your style.

        Also, it has been said that if your code needs comments, your code isn’t clear enough ;-) Code never lies, comments often do…

        • All good points. I actually didn’t know docblock was an industry standard. I checked it out after the release of this article because NUMEROUS people pointed it out to me.

          I believe I HAVE seen it before but honestly, I just don’t like the way it looks. Yes, it’s subjective. Yes, other devs may not like my type of commenting. No, I don’t care (as arrogant as it sounds) because I want GOOD LOOKING comments that are useful.
          I believe that good code may not NEED comments but I find them useful, in different ways. I think the examples I put up were a bit misleading as to what my beliefs are. For example, I’m not looking to have every line of code explained, nor even every function, or whatever else.
          What I AM looking for (mainly) is comment HEADINGS for sections. Such as in CSS, I like headings in CSS, it’s much easier to scan the document and find the right place. With that Sublime Text 2 map thing on the right, it’s beyond a breeze.
          Then, i would like to see a description of the section. A quick one. Two sentences.
          All structured well enough that comments don’t become a nuisance.
          As far as Laravel goes, the comments are basically a tutorial in itself for newbies. I appreciate that since I don’t know how Laravel works and going through it, I can figure out the entire framework without accessing external resources. The documentation is thorough and built in. Does that mean the code is not clear enough? I don’t think so but it does make the framework friendlier especially since it’s not machine readable. It’s HUMAN readable.

          • Juan Treminio says:

            Yeah, doing your own thing and not following an industry standard simply because something looks pretty to you is a horrible excuse.

          • I’m sorry but why should I follow something that I consider shit and doesn’t fulfill the requirements/needs I have for it? Seriously. This is a typical “If everyone jumps off the cliff, will you follow?”. Not even that, it’s like being handed a flat-head screw driver for a phillips screw when you have a phillips screwdriver in your pocket.

          • Anne kootstra says:

            Industry standards develop over time based on the lessons learned during that period. Knowing them should be expected, adhering to them should not require expanation. When you find yourself in a situation where both are occring, please consider your own position instead of lashing out to your peers.

          • I’m considering my own position. My article is not meant to be a lash out, more of a call for people to make more useful and prettier comments. Yes, prettier. And I’ve explained my reasons why. I have, so far, approached each commenter with a level head and without anger, always considering their own position.

            My last comment to Juan was an answer to what he said. Should I consider the standards if they don’t work for me? I don’t believe so. If I write documentation, I’ll most likely write it separately from my application (ie. not compiled from my comments) so do the standards matter at all in my situation? Nope. So why would I adhere to a commenting style that I find not only less attractive than Laravel’s but less useful to me.

            Better yet, many commenters (on different sites and here) mention how comments are useless and should be avoided altogether. If that is true, what is the harm in creating human-readable, pretty comments that assist during learning of the application and during coding?

            One thing that a lot of these people don’t realize that this isn’t exclusively a PHP thing. I mentioned bootstrap on purpose, It covers both JS and CSS neither of which have conventional rules nor a widely used doc creator (as far as I’m aware, you’re welcome to prove me wrong).
            Again, my position is considered. On one hand I have developers that want me to adhere to docblock standards so that my comments are machine readable and can create documentation. On the other hand, I have developers that want me to erase comments altogether and focus on making the application readable as is. Both sides have their arguments. And I fit in by adding good-looking comments that help VISUALLY separate code, that add human readable explanation for either novices or those that want a quick summary of what’s happening. Both sides aren’t happy with what I’m doing. It’s a bit bizarre.

          • Most languages use the Doc style commenting because

            1. editors parse and understand them (leading to better autocompletion)

            2. documentation generation tools parse and understand them (for generating searchable documentation)

            3. It provides a standard we all understand, instead of everyone inventing their own.
            Now note, no one says in particular how to make a PHPDoc comment pretty. But it gives a single way to provide semantical information which editors and documentation tools understand.

            If you can’t see the benefit of that and believe style should override substance, you’ll find most people won’t agree with you.

            By the way, pretty and readable are not the same thing. I’ve noticed people who spend too much time making their comments pretty then waste a lot of time updating said comments, or don’t update them enough. I prefer an easy to read, easy to write/update style. It tends to be more stable over time. This excludes excessive decoration like demonstrated here.

          • Alright, I’ll concede to those points.

            However, I do find the Laravel style comments easy to write and easier to read than DocBlock. When I say “pretty”, I do mean legible as well. I guess I’m a bit stubborn :)

  2. Docblocks tend to be the defacto standard in PHP and are readily parsed by a number of IDEs. Also worth noting is that PHP’s Reflection API allows you to read files and parse docblocks to create readable online documentation and static files.

    http://www.phpriot.com/articles/reflection-api

    Likewise, you can just use an existing solution like phpDocumentor 2 to generate these documentation files:

    http://phpdoc.org/

  3. calvintennant says:

    I’m just going to leave this here: http://www.stack.nl/~dimitri/doxygen/

  4. Prison of Mirrors says:

    What I don’t understand is that DocBlock looks pretty similar to your last example. You have the short description at the top, or just a brief one-liner. You then have the actual description of the function, class, etc. after which may be quite long but that really depends on what you’re documenting. You then have a list of all the arguments, their datatypes, if they’re required, and if there’s a default. You also have the return type, if any.

    Instead of pipes, they use asterisks. I really don’t see the difference (at least a considerable one). In addition, many IDEs and code editors have built-in support for DocBlock comments which provide tooltips, autocomplete, and code hinting. That’s not something that can be passed up.

    • Very good points. Seems like I was a bit stacked to fight everyone especially being pressured by one side not to comment at all and pressured by the other to only use DocBlock.

  5. Comments are a maintenance headache. As a general rule I would fall into the “comments are dangerous” camp. From my experience weaker programmers tend to read comments then the code, Great programmer tend to go the other way with code first and comments later.

    But I am not an anti-comment Nazi. It’s all about context and the platform you are working with. For example I strongly believe while working in a type-safe, OO language like c# with advanced tools like Resharper your code really should be self describing. If it is not you are either writing something unavoidably complicated (rare) or you need to restructure your code (common!). Your time is best spent fixing the underlying code structure problem not commenting the bad style.

    However if your language and tools do not provide good mechanisms for ensuring your code is self describing then commenting becomes an invaluable way of mitigating the insufficiencies of the language/platform you are using. A recent example I personally came across is IPTables firewall scripts, these are not particularly descriptive and opportunities for improving this are limited. In this case comments rule.

    There is one universal exception to comments being “bad” and that is API interfaces. This is where time and effort should be spent on ensuring comments are meaningful and structured to allow documentation to be generated and published.

    • Voice of reason. Nice to hear. I worked with C# for a small bit (a month/two) and found resharper extremely helpful. I don’t remember if the code was DocBlocked or not but I remember Visual Studio and hard-typed vars basically doing all the work for me.

      The article addresses languages that cannot be easily OOed (yet) such as javascript which does have Objects but can get messy at some point. Same goes for CSS which now can be used with SASS or LESS but I feel like still requires section headings for compiled versions.

      I wouldn’t spend too much time on commenting either that’s why I like that comment structure Laravel introduced for the dev. One thing to note is that Laravel uses Docblock compliant comments within its app.

      Code structure IS more important than comments but comments, I feel like, will still prevail. I also do want to include “weaker” programmers. I was there once, probably still am ;) I don’t read comments much anymore unless I’m really WTFing or when I need to figure out where I’m at in the app’s structure (again, headings!).

      How would you create proper documentation, btw, without docblock or some other comment-based compiler? I see that as one of the main reasons to comment your code.

      • Question: “How would you create proper documentation, btw, without docblock or some other comment-based compiler?”
        Answer: Panic :)

        After the panic subsided if I was doing serious work I either probably roll my own mechanism for extracting structured documents through some commenting convention or follow an approach similar to what you have described in this article. But it really is uncomfortable leaving the c#/resharper bubble.

        JS/CSS/HTML are special cases as the compatibility issues mean breaking “good practice” and the only option is to comment. A good example of this is phone browsers based on old webkit releases where the stack size is limited to around 100 or so levels of recursion without any local variables, with some data at each level and this is reduced significantly.

        This pretty much rules out any sensible OO in JS and was why we had to drop YUI in favour of jQuery for our internal frameworks.

  6. How to write comments well: don’t write them at all. Use speaking names, well segregated interfaces, thorough separation of concerns, small methods and small classes, and you won’t need comments.

    Remember: comments are the first part of code to bit-rot, and there’s no compiler to check them for you.

    The only reason to _maintain_ comments – you need to do maintenance on them too, if you decide to write them – is in library code from which you want to automatically generate documentation. However, fortunately in such cases each language/ide/documentation generation tool has its own standards, so you’re not in a position to choose. Why fortunately? Simple! It provides consistency, and at least syntax checking, although no semantic checking.

    And you don’t to write and maintain javadoc-like tags in libraries which are project-specific. If you are the creator of junit, wpf, boost or something similarly grandiose, you should of course find a cheap way to produce adequate documentation. This is not the case in 99% of all libraries being written.

  7. KimJoyFox says:

    I really appreciated this article! Comments, to me, are vital – not necessarily to explain everything that’s going on, but to at least give another developer (or you… after you forget) an overview of how the thing is coded. Ideally, I would always leave a roadmap at the top of my coding that explains the basic layout of the code (because there are a ton of different ways to accomplish the same thing), and separate the code using comment headings. They’re really just like using chapter and verse in the Bible. Sure, you could get by without them, but it makes it so much easier with them!
    All that to say, your post was helpful for me and fun to read.. as were the comments!

  8. Yow. You’re really taking some heat here.

    Personally, I work with a ton of code, and I’ve never worked in any language that wouldn’t both benefit from good comments, and be totally trashed by bad ones.
    Of course, I don’t really agree with any avocation that people SHOULD write pretty comments. But I don’t disagree with the idea that, if you’re going to write comments, they SHOULD be pretty.

    And, of course, ‘pretty’ is subjective, but there are some, nigh-universal, aesthetic standards. I don’t think anyone could disagree that the examples you provided were pleasing to the eye. They may have their faults, like not being machine readable, but they are absolutely, pretty.

    Anyway, I dig the article. Thanks for putting this out there. Long live pretty code, in all forms!

Trackbacks

  1. [...] SourceURL: http://antjanus.com/blog/web-design-tips/best-comment-separator/ [...]

  2. [...] How To Write Code Comments Well - Code organization is a huge thing, especially for developers (because they deal with code), and often times it’s a philosophical debate as to how code should be documented, if spaces should be used instead of tabs, what kind .. [...]

  3. [...] myself, to keep in the habit of it and to get my ideas down. However, when I wrote the article on “pretty commenting”, I got an overwhelming response and with that a ton of criticism. It was hard to direct where that [...]

  4. […] How To Write Code Comments Well - Code organization is a huge thing, especially for developers (because they deal with code), and often times it’s a philosophical debate as to how code should be documented, if spaces should be used instead of tabs, what kind .. […]

Add Your Comment