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.
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:
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:
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
The post How to Comment Your Code Like a Pro: Best Practices and Good Habits appeared first on Elegant Themes Blog.