Some time ago, Remkus de Vries wrote a post on standards for code snippets. I’m a true fan of the WordPress Coding Standards, so hit me if any of my code snippets are not in line with those standards. I’m not going to argue Remkus’ opinion that code snippets should be written according the WordPress Coding Standards.
He also did a great job pointing out that there is a lack of comments in (WordPress related) code snippets around the web. I tend to provide the snippets that I published with some comments, but I do not follow any standards while doing that.
The thing that triggered me to write my take on code standards, is Otto’s comment:
No. Never.
Snippets I post are not meant to be working code. They are not tested, not run, and not meant to be used as copy-pasta. Usually I type them on the fly, off the top of my head. They’re a demonstration only, to show somebody how to do something.
Also, Github is the tool of the devil.
So no, not going to happen. Not now, not ever. No.
I’m not going to reply on this statement about Github – and later on Git too. Yes, I’m a Git fan too, will get back on that later. But the main topic in his comment is very interesting.
Are code snippets ready to use?
Even with proper documentation, are all code snippets ready to use? Most of the time I can’t tell, based on just the code. The documentation adds some more value to the snippet and I’m more likely to use it.
But still, the question is: Does the snippet work? There is no way to see that the code has been tested, not to mention at what version of WordPress it has been tested. Yes, the author of the post can mention it. But we all know that code is shared in various ways, so the original post might not always be available.
A new documentation standard might come in hand here!
Introducing the @tested documentation tag
What if everyone who wants to publish ready to use snippets, adds an extra tag to their docblock to indicate that it has been tested to a certain version of WordPress?
Let me add this new tag to the function Remkus used in his post:
<?php
add_filter( 'body_class' , 'ft_add_guest_body_class' );
/**
* Adds a body class for guests.
*
* @author Remkus de Vries
* @link http://remkusdevries.com/when-sharing-wordpress-related-code-snippets-i-can-haz-standards-please/
* @tested WordPress 3.2.1
* @param array $classes Existing body classes
* @return array Amended body classes
*/
function ft_add_guest_body_class( $classes ) {
// add 'not-loggedin' to the $classes array
if ( ! is_user_logged_in() )
$classes[] = 'not-logged-in';
// return the $classes array
return $classes;
}
With this new documentation tag in place, we can clearly see up to what version of WordPress the code has been tested on. If the code hasn’t been tested, then just leave out the docblock and post the snippet like you’re used to (so Otto can just continue posting his awesome snippets on the web, without having to test them ;) ).