Advertisement
Creative Coding

A Case for Code Comments: The Server-Side

by

When it comes to writing code, regardless of the language or platform that's being used, we developers tend to be divided on how much or how little we should comment our code.

On one hand, there are some who believe that code should be self-documenting. That is, it should be written clear enough such that it doesn't need comments.

On the other hand, some believe that everything should be commented. That is, there should be comments for every class, every function, every block, and every line.

Then, of course, there are those who fall in the middle. In fact, some developers only comment areas of their code that may be confusing rather than picking the all-or-nothing approach outlined above.

When it comes to writing code for WordPress, we have the WordPress Coding Standards to provide a standard by which we should be writing our code; however, it doesn't provide a strong case for or against code comments.

In this series of articles, I'm going to provide a case for code comments. Specifically, I'm going to cover why they matter, a recommendation for how to do so in the context of the standard WordPress required files (for both themes and plugins), and for how to do so for HTML files, stylesheets, and JavaScript files.


Why They Matter

Before looking at the various parts that make up a WordPress project, I think that it's important to discuss why code comments even matter. Sure, most of us know that it's to provide a short explanation as to what's going on with the code, but the implications are greater than that.

Despite the fact we have standards by which we should be writing our WordPress-based code, some developers treat them as "recommendations," let alone those who aren't even aware of them. Regardless of how well (or how bad) you write your code, it's still code.

After all, if it were easy to understand, it wouldn't be called code (and we wouldn't need comments).

I don't believe that we should write code comments only with others in mind, either. I think that we should write them for ourselves just as much. When you revisit code for the first time after a significant amount of time has passed, it's most likely that you've become a better programmer, picked up a few new techniques, and/or moved on from how you used to write code. Thus, it can be difficult to discern what you were trying to do.

And if it's difficult for the author of the code to follow, what hope is there for other developers who are contributing, extending, or improving the code?

Ultimately, comments should be written to both ourselves and others who may interact with our code. They should be clear, concise, and should provide any information necessary that a developer would need to know in order to work with the given section of code. This includes any information that references code in other files (be it server-side or client-side), too.

With that said, I'd like to cover a few reasons and strategies for commenting all of the files that go into creating a WordPress theme, plugin, or application.


On the Server-Side

Depending on your project, the files that you're required to include vary. For the purposes of this article, I'm assuming that you're including PHP files, HTML files, stylesheets, and JavaScript files simply to make sure that all bases are covered. In this article, we'll discuss the server-side language - that is, PHP - and in the next article, we'll review client-side languages.

When it comes to commenting our PHP files, there are several requirements that we must follow:

Other than this, there's really very little commenting required, so there's obviously room for improvement.

PHPDoc

When it comes to commenting code in PHP, there's actually a suggested way of doing so - PHPDoc. Similar to the WordPress Coding Standards, PHPDoc is a standard for commenting (or documenting) PHP code. It provides a number of conventions all of which are applicable to WordPress, but a subset of which I see used regularly.

Templates

WordPress supports two types of template files:

  1. Basic theme template files, such as the index, single, page, archives templates, and so on.
  2. Custom page templates which are files that we developers create that can be applied to existing pages in the WordPress UI.
  3. Partial templates which are fragments of templates that can be reused throughout other templates.

When it comes to documenting template files - regardless of which type of template - I always try to provide header information that defines the name of the file, the purpose of the file, the package - or theme or plugin - of which it's a part, and how long it has existed in the project.

For example:

/**
* Template Name:	Featured Projects
*
* The template used for the 'Featured Projects' area of the homepage. Loops through the 'Featured Projects' post type and pulls the three most recent entries.
*
* @package	Project Theme
* @since	1.0
*/

As you can see, I've provided the required Template Name for the file, but I've also given a short description of what's happening within the file. I've also used the @package and @since directives to help give further clarity.

The @package directive, at least in the context of WordPress, represents the name of the theme or plugin of which this particular file is a part.

The @since directive represents how long the template has existed in the project. In the case above, it's obviously been in the project since its initial release, but it's not at all uncommon to add files as a theme or plugin matures thus resulting in a different version number appearing as this value.

Because of the nature of the basic template files such as the index, single, page, archives templates, and so on, there's no need to define a "Template Name," but the description, package, and since directives are still relevant.

Functions

Documenting functions is very similar to documenting templates. Although they don't require a specific tag - such as "Template Name" - they should still include a description of the purpose of the function and the @since directive.

There are also two additional directives a function may optionally include:

  • @param which describes the type and description of a parameter that the function accepts
  • @return which describes the type and description of what the function returns

Of course, functions don't always accept parameters and functions don't always return values hence the reason these two directives are optional.

Assuming that you have a function that supports both of the above directives, here's how you should expect the documentation to appear:

/**
 * Programmatically inserts a page into the database.
 *
 * @param	$title			The title of the page. The lowercase variant also serves as the page slug.
 * @param	$template_name	The name of the template file located in the 'templates' directory.
 * @return					The ID of the page that was created
 * @since	1.0
 */

For more information about each of these directives, you can review the PHPDoc tags; however, you can see just how helpful this can be for working on a theme or plugin - it takes a lot of the pain out of having to discern what you or another developer were trying to accomplish with a given function.

Lines and Blocks

Though there are few recommendations or actual standards for documenting blocks of code, I still believe that it's useful especially when it comes to more complicated loops or conditionals.

All of this can be demonstrated in the following example: Let's assume that we need to setup a custom query to loop through post meta data and then delete it if a certain key and/or value is found. This would require the following steps:

  1. Setting up the arguments for the query
  2. Executing the query
  3. Looping through the results
  4. Conditionally deleting the post meta data
  5. Resetting the query

This example will document both single lines as well as conditionals. First, let's take a look at the source code and then we'll review what it's doing just after it:

// Setup arguments to retrieve all published posts
$arguments = array (
	'post_type'		=>	'post',
	'post_status'	=>	'publish',
	'numberposts'	=>	-1
);

// Instantiate the query
$posts_query = new WP_Query( $arguments );

// If any posts are found, loop through them
if( $posts_query->have_posts() ) {

	while( $posts_query->have_posts() ) {

		$posts_query->the_post();

		/*
		 * For each piece of post meta that is found, store its values in
		 * the $meta_key and $meta_value for us to check.
		 */
		foreach( get_post_meta( get_the_ID() ) as $meta_key => $meta_value ) {

			/*
			 * There may be multiple meta keys (such as tweet_url_0, tweet_url_1)
			 * so we need to check to see if the 'tweet_url' is located in the
			 * $meta_key.
			 *
			 * If so, we can delete the post meta data
			 */
			if ( false != strstr( $meta_key, 'tweet_url' ) ) {
				delete_post_meta( get_the_ID(), $meta_key );
			} // end if

		} // end foreach

	} // end while

} // end if

// Reset the custom query so not to interfere with any other queries or The Loop
wp_reset_postdata();

Ideally, the  comments above should provide all of the documentation and explanation necessary to understand what's going on in the code. Perhaps the only thing that may be required is understanding of the strstr function.

The key point that I'm trying to make with the code above is that if we're documenting single lines, then it's best to stick with the single line convention - that is, the // - but if we're writing a comment that spans multiple lines, it's always best to use the multiline comment - that is, the /* */.

Notice also that not every single line has to be commented. Rather, blocks (or chunks) of code can be explained in a multiline comment that documents what's about to happen in the following source code.

Of course, this isn't a standard or a preferred way to do things. It's merely a strategy that I've seen used, that I appreciate, and that I use myself.


Generating Documentation

phpDocumenter

If you end up following the conventions set forth in PHPDoc, then there are a number of utilities that can generate documentation pages for your work. Arguably, the most popular tool is phpDocumentor.

In short, phpDocumentor is a utility that will go through your source code looking for properly formatted PHPDoc code comments (specifically on classes and functions), and will then generate a set of styled pages capturing the information in your comments.

This makes shipping developer-oriented documentation with your application a cinch.


Conclusion

Throughout this article, I've covered why I believe code comments should be something that all developers should include in their code. Though the WordPress Codex defines a basic set of comments required for our work and/or to interface with the WordPress application, there's obviously more work that we can do to improve the clarity of our code.

The thing is, we've only covered half of it. So, in the next article, we'll take a look at documenting markup, JavaScript, and styles.


Resources

Related Posts