How to Comment Your Code Like a Pro: Best Practices and Good Habits

Last Updated on September 22, 2022 by 12 Comments

How to Comment Your Code Like a Pro: Best Practices and Good Habits
Blog / WordPress / How to Comment Your Code Like a Pro: Best Practices and Good Habits

Writing code is a lot like writing prose. Every person does it a little differently, and because of that, we all have a distinct voice when our code is read. We have different naming conventions and different problem-solving logic. We all think our code makes sense — especially if it works — but someone else might not. To combat this, we all need to get better at source code commenting. That way, whoever comes next to the project will have a clear path to understanding and improving/fixing our code.

How to Comment Code – The Basics

To begin with, let’s make sure that we’re all on the same page regarding what comments are. In this article, we’ll be discussing in-line comments within the scripts themselves. Stuff like this in a CSS file, for instance, where the readable code is broken up by comments that are ignored by the processors.


/** Body Element Styling **/

body {color:red;}

h1 {size:17px;}


/** Sidebar Widget Styling**/

#email-signup-1 {text-transform:uppercase;}

Each programming language has a different way of commenting in the source code. PHP and HTML and JavaScript and C# all have slightly different symbols that begin and end code. While there are some language-specific practices, too, there are more shared than not.

We’ll discuss some of the different kinds of comments that you will run across, their uses, and best practices (or maybe just good habits to get into) when using them yourself.

The basics tenets of commenting your code are simple:

  • Make them brief
  • Keep them relevant
  • Use them liberally, but not to excess

If you can keep those in mind, you’ll be doing pretty okay.

A Moment to Discuss Naysayers

Very briefly, let’s touch on the source code commenting naysayers. There is a not-small subset of developers who believe that commenting your code should be an exceptionally rare occasion. That when you need source code comments, that’s an indication that your code is weak in some way. That your naming conventions, logic, or something else isn’t as transparent as it should be.

And, to be fair, this argument makes a certain amount of sense. However, a number of circumstances exist that make more than enough of an argument to include documentation in the form of comments, regardless of how well-written and factored your code is.

The primary ones being that you’re not always going to be the one working on the project, and you can’t guarantee how experienced the next person will be. Even if you write great code, there’s a chance for confusion and ambiguity.

Header Block Documentation

If you look in some files, the code doesn’t begin immediately because there’s a large header in the file that describes what its purpose is, the variables, functions, methods, and so on. They might even be in a giant box around it to call your attention to it.

This isn’t a good habit to get into. Because it’s kind of pointless. Well, it’s really pointless, actually.

best practices for commenting your code

Also, look at the example above: the comment header is absurdly long. There are very rarely reasons to do that. So don’t.

Anything that you would put in that file should be put into your documentation anyway. Having it in a comment is redundant. Additionally, the end user is likely never going to get into your source code, so the comment would only be seen by other developers (or hardcore users of the software who already know the documentation).

Plus, whenever the documentation changes, you have to change it in that file. It’s easy to miss a step, and then your codebase can seriously get fouled up.

When Header Comments Are Useful

Header comments are useful in source code for simple explanations of what to expect in that file. For instance, this is a script that comes with a game development engine called RPG Maker, and the core JS file that controls each game scene begins like this:


//=============================================================================
// rpg_scenes.js v1.6.2
//=============================================================================

//=============================================================================

/**
 * The Superclass of all scenes within the game.
 * 
 * @class Scene_Base
 * @constructor 
 * @extends Stage
 */
function Scene_Base() {
    this.initialize.apply(this, arguments);
}

Scene_Base.prototype = Object.create(Stage.prototype);
Scene_Base.prototype.constructor = Scene_Base;

Additionally, note that the version number is listed at the very top. Do this. Do not, however, provide a comprehensive list of dates on which the file was altered and new versions published. That is recorded in Git or other version control software, and it should be available to anyone who needs that information. The version number is sufficient for most people who would be looking at this file.

In-Line Documentation

The most common type of source code comment is the in-line comment. There is a fine line with these between doing it right, going overboard, or being too sparing with them. It’s a balance you have to just learn over time, but there are some pretty good rules of thumb to consider.

Do not do line-by-line comments. In-line commentary is one thing. Line-by-line commentary makes the code look almost unreadable. See below:



function sourceCodeComment () { //calls a function
  var comment = document.getElementbyID("Code Comment").value; // declares a variable
  if (comment != null && comment != '') {  //starts an if statement to evaluate if there's a comment
        return console.log("Thank you for your comment.") //prints a string to the console
}

That’s overkill. If you have to, do it before or after the function. But not on each line. It is obtrusive and generally unhelpful. A comment before the function (or element) is good for organization and clarity. More than that should go into the documentation.

If you feel like it’s necessary to document, something like this will suffice.


//checks to see if there's a comment. If so, returns a thank you message.

function sourceCodeComment () {
  var comment = document.getElementbyID("Code Comment").value; 
  if (comment != null && comment != '') { 
        return console.log("Thank you for your comment.")
}

The naysayers will mention that even this kind of commentary is redundant because good naming conventions for your functions, variables, and methods will make the code readable. That is true to a point, but if you’re going for keeping ambiguity to its absolute minimum, a quick comment is the way to go.

It’s Okay to Put Warnings in Source Code Comments

Sometimes the obvious solution to a problem doesn’t actually solve the problem. In these cases, developers who come to a project later in development may look at a file and consider refactoring it take in that obvious solution. Doing so will be a complete waste of time.

Or maybe something else will come up in the future, and they try to call a function that breaks everything and brings the project to its knees.

Regardless, if you have something that you know for a fact won’t work and that you know other people will likely try in the future, it’s okay to warn them about it.


// Don't bother trying to use goodCodeComment() here. 
// It breaks bestPractices() despite seeming like the best option.
// We went with simplyOkayCodeComment() instead.

function simpleOkayCodeComment() {
	//some kind of code goes here
}

Also, did you notice what we did in that example? We not only gave the warning to future devs, but included a placeholder comment in the middle of a function. Because source code comments are ignored, you can use them to keep placeholder text in the file (sort of as an annotation to yourself to return there, or as an example to someone as an explanation).

Don’t Be a Jerk

I have seen this happen before, especially in open-source projects that weren’t moderated terribly well. Someone will find a less-than-stellar snippet of code and use a comment to denegrate the author.


//This function looks like it was written by a third grader.
//It shouldn't work, but it does somehow. I don't want
//to fix it because I want you all to see how bad it is.

Or maybe they do fix the code, but include the code, simply commented out, so that they can show off their code, while at the same time mocking the previous author.


//The old code was so bad, I just had to leave it here for you to see.
//I fixed it. My code is below. But look at this.

// function theMatrix() {
//	var neo = maybeTheOne.data + theOracle.data
//	if theOne() !== neo
//		return console.log("you got the gift, but it looks like you're waiting for something")
// }

Just make sure that you never do this. Even if you think you’re being funny or that it makes you look good, it isn’t and it doesn’t.

The real use of commenting out code is for you to keep that code handy while trying something else. Or to give an example of what didn’t work before so someone doesn’t try it again fruitlessly.

Source Code Comments for WordPress

In general, WordPress is run on four different languages. HTML, CSS, PHP, and JavaScript. Making sure that use the right characters for the comments is imperative.

For HTML:

<!-- comments go here and can be single or on multiple lines --></em>

In CSS:

/* Any number of lines will be a comment until the comment is closed */ 

Both PHP and JavaScript have the same methods for doing single- and multi-line comments:

<?php function(); // a single line comment is like this ?>

or

<?php /* unlike above, you can carriage return
				and no matter how many lines you use,
					the comment won't stop until closed */

Conclusion

If you’re in the trenches day in and day out, writing code and pushing to GitHub, your organization may have a style guide for comments they want you to follow. If they don’t, however, or you are on your own, keeping this stuff in mind will not only make your job easier in the future, but will also help out anyone who comes after you, too.

What are your tips and tricks for getting the most out of commenting your code?

Article featured image by Skillup / shutterstock.com

Divi

Want To Build Better WordPress Websites? Start Here! 👇

Take the first step towards a better website.

Get Started
Divi
Premade Layouts

Check Out These Related Posts

What Size Image To Use On WordPress (Key Factors & Tips)

What Size Image To Use On WordPress (Key Factors & Tips)

Posted on November 17, 2024 in WordPress

Are you experiencing slow website loading speeds? The low website speed could result from many factors, and large image sizes are one of them. If you have a website with a great deal of content, image size could likely be one of the factors behind your site’s slow speed. Hence, it is...

View Full Post
How to Make a Responsive Website in 2024 (No Coding)

How to Make a Responsive Website in 2024 (No Coding)

Posted on November 9, 2024 in WordPress

Is your website not performing well on mobile devices? Poor layout or slow loading times can cause users to leave your site before they even engage with your content. In today’s mobile-first world, a responsive website is no longer just an option—it’s a necessity. Whether you’re...

View Full Post

12 Comments

  1. I agree that database storage is a must-have in order to be a serious alternative to third party plugins like Gravity Forms.

  2. Thanks for sharing about how to comment your code.
    If you can keep these simple points in mind you’ll be doing pretty okay: make them brief, keep them relevant and use them liberally. Keeping this stuff in mind will not only make your job easier in the future but will also help out anyone who comes after you, too.

  3. really informative article anyone how to know basic of coding can work all on this theme

  4. Great article! Does anyone know of a code editor or even an extension that track changes?

    • ^ Meaning, an extension or editor that has the functionality similar to an audit report or how Word tracks changes in a document?

      • Not quite like that, I don’t. There might be a VS Code extension for it, but I honestly haven’t seen one in my time of using it.

        You can, however, use git to do this, where each commit and push gives you a ‘diff’ that you can check what additions and subtractions were made in green and red. You can see what it looks like in this screenshot: https://www.elegantthemes.com/blog/wp-content/uploads/2019/04/000-gitdiff.png

  5. Thank you for a very helpful post.

  6. I like to introduce a section of styling with a bolder headline, then comment each function, especially in the child themes I sell or in my Divi tutorials. My method for CSS is as follows:

    /*SLIDER MODULE STYLING
    *************************************************/

    /*slider arrows*/
    .code here {
    example: okay;
    }

    • I’ve seen those a lot. I honestly didn’t even think of that being any different as a typical header because I’m so used to seeing it, haha. I suppose I prefer those, too, now that you mention it. 🙂

      The ones I do for my personal use tend to be /********* Headers *********/

    • Yep this is what i do to. Additionally i add @ when it is something for responsiveness like this: /*@@@@ SLIDER MODULE RESPONSIVE @@@@*/

  7. hi, good post, i however personnaly dislike inline comment and rather like the multi lines comments. It’s good to mention that commenting each single line of code, does the contrary of helping to understand the code.

    It’s also a good pratice (for intellisense) to use comments decorators like : @param, @return. That could help to debug better the code specially for PHP Projects.

    Cheers.

    • You’re totally right. I always like opening a file and seeing @param there for me to hone in on.

Leave A Reply

Comments are reviewed and must adhere to our comments policy.

Join To Download Today