Source Code Comment Styling: Tips and Best Practices

By . Filed in Web Design

Developers who have spent any time on large projects understand the importance of code comments. When you’re building many features into the same application, things tend to get complicated. There are so many data bits including functions, variable references, return values, parameters… how are you expected to keep up?

code commenting
(Image Source: Fotolia)

It should come as no surprise that commenting your code is essential, both solo and team projects. But many developers are unaware of how to go about this process. I’ve outlined some of my own personal tricks to creating neat, formatted code comments. Standards and comment templates will vary between developers – but ultimately you should strive towards clean and readable comments to further explain confusing areas in your code.

We should begin discussing some of the differences in comment formatting. This will give you a better idea of just how detailed you can become with project code. Afterwards I’ll offer some specific tips and examples which you can start using right away!

Comment Styles: An Overview

It should be noted that these ideas presented are merely guidelines towards cleaner comments. The individual programming languages do not set forth guidelines or specifications for how to setup your documentation.

That being said, modern-day developers have grouped together to format their own system of code commenting. I’ll offer a few mainstream styles and go into detail of their purpose.

Inline Commenting

Practically every single programming language offers inline comments. These are limited to single-line content and only comment the text after a certain point. So for example in C/C++ you begin an inline comment like this:

// begin variable listing
var myvar = 1;
..

This is perfect for chiming into the code for a few seconds to explain possibly confusing functionality. If you are working with a lot of parameters or function calls you may place a slew of inline comments nearby. But the most beneficial use is a simple-minded explanation for small functionality.

if(callAjax($params)) { // successfully run callAjax with user parameters
 ... code 
}

Notice above all the code would need to be on a new line after the opening bracket. Otherwise it would all be caught on the same comment line! Avoid going overboard since you generally don’t need to see single-line comments all the way down your page, but particularly for confusing junctions in your code, these are much easier to drop in last minute.

Descriptive Blocks

When you need to include a large explanation generally a single liner won’t do the trick. There are pre-formatted comment templates used in about every area of programming. Descriptive blocks are most notably seen around functions and library files. Whenever you setup a new function it is good practice to add a descriptive block above the declaration.

/**
  * @desc opens a modal window to display a message
  * @param string $msg - the message to be displayed
  * @return bool - success or failure
*/
function modalPopup($msg) {
...
}

Above is a simple example of a descriptive function comment. I’ve written a function presumably in JavaScript called modalPopup which takes a single parameter. In the comments above I’ve used a syntax similar to phpDocumentor where each line is preceded with a @ symbol followed by a selected key. These are not going to affect your code in any way, so you could write @description instead of @desc with no changes whatsoever.

These small keys are actually called comment tags which are documented heavily on the website. Feel free to make up your own and use these as you wish throughout your code. I find they help to keep everything flowing so I can check important information at a glance. You should also notice I’ve used the /* */ block-style commenting format. This will keep everything much cleaner than adding a double slash beginning at each line.

Group/Class Comments

Aside from commenting out functions and loops, block areas aren’t utilized as frequently. Where you really need strong block comments are at the head of your backend documents or library files. It’s easy to go all-out and write solid documentation for every file in your website – we can see this practice in many CMS such as WordPress.

The very top area of your page should hold comments regarding the file itself. In this way you can quickly check where you’re editing when working on multiple pages at the same time. Additionally you can use this area as a database for the most important functions you’ll need out of the class.

/** 
  * @desc this class will hold functions for user interaction
  * examples include user_pass(), user_username(), user_age(), user_regdate()
  * @author Jake Rocheleau jakerocheleau@gmail.com
  * @required settings.php
*/
abstract class myWebClass { }

You can see I’ve used just a small sample class for the fake myWebClass code. I’ve added some meta information with my name and email address for contact. When developers are writing open source code this is generally good practice so others may contact you for support. This is also a solid method when working in larger development teams.

The tag @required isn’t something I’ve seen used elsewhere. I have kept up with the format in a few of my projects, only on pages where I’ve customized a lot of methods. Whenever you include pages into a file they must come before you output any code. So adding these details into the main class comment block is a good way to remember which files are needed.

Front-end Code Commenting

Now that we’ve covered 3 important comment templates, let’s look at a few other examples. There are many frontend developers who have moved from static HTML into jQuery and CSS code. HTML comments aren’t as purposeful compared to programming applications, but when you’re writing style libraries and page scripts things can get messy over time.

css
(Image Source: Fotolia)

JavaScript follows a more traditional method of commenting similar to Java, PHP, and C/C++. CSS only utilizes the block-style comments delineated by a slash and asterisk. You should remember that comments will be openly displayed to your visitors, since neither CSS nor JS is parsed server-side, but either of these methods works great for leaving informative tidbits in your code to go back over.

Specifically breaking up CSS files can be a chore. We are all familiar with leaving an inline comment to explain a fix for Internet Explorer or Safari. But I believe CSS commenting can be used at the level jQuery and PHP use them. Let’s delve into creating style groups before touching upon some detailed tips for code commenting.

CSS Style Groups

For those who have been designing CSS for years it almost comes as a second nature. You slowly memorize all the properties, syntax, and build your own system for stylesheets. Through my own work I have created what I call grouping to pair similar CSS blocks into one area.

When going back to edit CSS I can easily find what I need in a few seconds. The way you choose to group styles is entirely up to you, and that’s the beauty of this system. I’ve got a few preset standards which I’ve outlined below:

  • @resets – taking away default browser margins, padding, fonts, colors, etc.
  • @fonts – paragraphs, headings, blockquotes, links, code
  • @navigation – the main core website navigation links
  • @layout – wrapper, container, sidebars
  • @header & @footer – these may vary based on your design. Possible styles include links and unordered lists, footer columns, headings, sub-navs

When grouping stylesheets I’ve found the tagging system can help a lot. However unlike PHP or JavaScript I use a single @group tag followed by a category or keywords. I’ve included 2 examples below so you can get a feel for what I mean.

/** @group footer */
#footer { styles... }
/** @group footer, small fonts, columns, external links **/

You could alternatively add a bit of extra detail in each comment block. I choose to keep things simple and straightforward so the stylesheets are easy to skim. Commenting is all about documentation so as long as you understand the writing it’s good to go!

4 Tips to Better Comment Styling

We’ve spent the first half of this article looking at the various formats for code commenting. Let’s now discuss some overall tips to keeping your code clean, organized, and easy to understand.

1. Keep Everything Readable

Sometimes as developers we forget that we’re writing comments for humans to read. All of the programming languages we understand are built for machines, so it can be tedious to convert into plain written text. It’s important to note that we aren’t here to write a college-level research paper, but just leaving tips!

function getTheMail() {
	// code here will build e-mail

	/* run code if our custom sendMyMail() function call returns true
	   find sendMyMail() in /libs/mailer.class.php
	   we check if the user fills in all fields and message is sent! */
	if(sendMyMail()) { return true; // keep true and display onscreen success
    }
}

Even just a couple of words are better than nothing. When you go back to edit and work on projects in the future it’s often surprising how much you’ll forget. Since you aren’t looking at the same variables and function names every day you tend to slowly forget the majority of your code. Thus you can never leave too many comments! But you can leave too many bad comments.

As a general rule of thumb, take some time to pause and reflect before writing. Ask yourself what is most confusing about the program and how can you best explain it in “dummy” language? Also consider why you’re writing the code exactly as you are.

Some of the most confusing errors pop up when you forget the purpose of custom-built (or 3rd party) functions. Leave a comment trail leading back to a few other files if this will help you remember functionality easier.

2. Alleviate Some Space!

I cannot stress enough how important whitespace can be. This goes doubly true for PHP and Ruby developers who are working on massive websites with hundreds of files. You will be staring at this code all day long! Wouldn’t it be great if you could just skim through to the important areas?

$dir1 = "/home/";                 // set main home directory
$myCurrentDir = getCurDirr();     // set the current user directory
$userVar = $get_username();      // current user's username

In the example above you’ll notice the extra padding I’ve placed between comments and code on each line. As you are scrolling through files, this style of commenting will clearly stand out. It makes finding errors and correcting your code hundreds of times easier when variable blocks are so clean.

You could perform a similar task on the code inside of a function where you’re confused about how it works, but this method would eventually clutter your code with inline comments, and that’s the exact opposite of orderly! I recommend in this scenario adding a large block-line comment around the area of logic.

$(document).ready(function() {
        $('.sub').hide(); // hide sub-navigation on pageload
		
        /** check for a click event on an anchor inside .itm div
              prevent the default link action so the page doesn't change on click
              access the parent element of .itm followed by the next .sub list to toggle open/close
        **/ 
		
        $('.itm a').live('click', function(e){
        e.preventDefault();
        $(this).parent().next('.sub').slideToggle('fast');
       });
});

This is a small bit of jQuery code targeting a sub-menu sliding navigation. The first comment is inline to explain why we are hiding all the .sub classes. Above the live click event handler I’ve used a block comment and indented all the writing to the same point. This makes things prettier rather than run-on paragraphs – especially for others reading your comments.

3. Comment While Coding

Along with proper spacing this may be one of the best habits to get into. Nobody wants to go back over their program after it’s working and document every piece. Most of us don’t even want to go back and document the confusing areas! It really does take a lot of work.

comment while coding
(Image Source: Fotolia)

But if you can write the comments while you’re coding everything will still be fresh in your mind. Typically developers will get stuck on a problem and scour the web for the easiest solution. When you hit the Eureka moment and solve such a problem there is generally a moment in clarity where you understand your previous errors. This would be the best time to leave open and honest comments about your code.

Additionally this will give you practice to getting used to commenting all of your files. The amount of time required to go back and figure out how something works is much larger after you’ve already built the function. Both your future self and your teammates will thank you for leaving comments ahead of time.

4. Dealing with Buggy Errors

We can’t all sit in front of the computer for hours writing code. I suppose we can try, but at some point we need to sleep! You will likely have to part ways with your code for the day with some features still broken. In this scenario it is crucial that you leave long, detailed comments about where you left things off.

checking code
(Image Source: Fotolia)

Even after a fresh night’s sleep you may be surprised with how difficult it can be to get back into the swing of coding. For example if you’re building an image upload page and have to leave it uncompleted, you should comment about where in the process you left off. Are the images uploading and being stored in temp memory? Or maybe they aren’t even recognized in the upload form, or maybe they are not displayed properly on the page after upload.

Commenting errors is important for two main reasons. First you can easily pick up where you left off and try again fresh at mind to fix the problem(s). And secondly you can differentiate between the live production version of your website and the testing grounds. Remember that comments should be used to explain why you’re doing something, not exactly what it does.

Conclusion

Development for web apps and software is a fulfilling practice, albeit a difficult one. If you are one of the few developers who truly understands building software then it’s important to mature with your coding skills. Leaving descriptive comments is just good practice in the long run, and you’ll likely never regret it!

If you have suggestions for clearer code commenting, do let us know in the discussion area below!

Author:

Jake is a user experience designer for both web and mobile platforms. Having over 4 years of freelance projects under his belt, he frequently writes articles on topics of modern design trends and social media. You can check out some of his work on Dribbble or follow his tweets @jakerocheleau.

Advertisement