Respect the Craft: Top 5 Basic Coding Practices

2 Comments

Apr 17, 2012

Tutorials
John Manning
Respect the Craft: Top 5 Basic Coding Practices

To be honest, I originally wanted to title this post “Top 5 Coding Annoyances.” But that's pretty negative, huh? So I decided that it would be perfectly reasonable to turn things around and focus on the positive. The inside joke is that the items on the list haven’t changed at all. In the end, they’re all about consistency, organization, and taking pride in what you produce. As WordPress likes to remind us, “Code is Poetry.”

This thinking falls in line with Matt Taylor's recent post regarding "Back of the Cabinet Mentality." Your job isn't done just because the site looks good. It's important to understand that the little details are actually a big deal, and that your projects will only benefit from being thorough. Take some time, do it correctly!

And now, here are the necessary disclaimers:

  • This is written from a CSS / jQuery / PHP perspective since that’s what I use. But these principles are general enough that they can easily be applied to other languages.
  • Writing good examples is difficult. Bear with me!

----

5. Indentation / Spacing

Yuck

.css{margin:20px 0;color:#eee;background-color:#fff;}

I'm surprised that I used to employ this method. I was under the impression that short was sweet. I would then indent the declarations themselves to mimic the HTML structure. But then I realized that (quite obviously) the power of CSS is that it can apply to multiple elements, and that there wouldn't always be a 1:1 relationship between declarations and elements. So I scrapped it.

Better

.css { margin:20px 0; color:#eee; background-color:#fff; }

This is pretty similar to the above approach, but at least you can recognize the properties a little more quickly.

Preferred

.css {
    margin: 20px 0;
    color: #eee;
    background-color: #fff;
}

Yes, the preferred syntax is going to make your stylesheets longer. You could look into using a preprocesser like SASS if you want to condense things. But this is all about readability. While a style with three properties is pretty basic, browser-specific CSS3 declarations quickly make things more complicated. Give yourself and your code room to breathe. It's zen.


4. Consistent Syntax

Yuck

function showExample($var, $var2 = false) {
    $foo = get_some_value($var);
    if ( $var2 == TRUE )
    $bar="some value";
}

Forgive my nonsensical function. If you can muster a willing suspension of disbelief and just focus on the syntax, you'll see that this is a mess.

Better

function show_example($var, $var2 = FALSE) {
    $foo = get_some_value($var);
    if($var2) {
        $bar = "some value";
    }
}

At least the basics are covered. For function names, pick one: camel case OR underscored. The same goes for boolean values: choose either lowercase OR uppercase. Also, I don't think there's ever a situation in which omitting curly brackets helps with readability. Finally, figure out where you're going to use spaces around parentheses and operators and stick to it.

Preferred

function show_example($var, $var2 = FALSE)
{
    $foo = get_some_value($var);

    if($var2)
    {
        $bar = "some value";
    }
}

Again, this is going to take up more room than the other methods. Providing a line for all curly brackets is actually pretty new to me, but I think it helps immensely.


3. jQuery Function Declarations

Preferred

function show_example() {
    // Do stuff
}

function do_something_else() {
    // Do more stuff
}

$(function(){
    if($('.some_class').length) {
        show_example();
    }
    do_something_else();
});

This one's a bit more difficult to explain, so I'm foregoing the lesser examples. Basically I've come to enjoy writing a unique function for everything that javascript might do and then calling those functions conditionally at the bottom of the page when the DOM has been loaded. This allows me to quickly see what functions are going to fire and how they're triggered. Previously, I declared $(function(){}) at the top of the page and placed everything inside of it. But I think this new approach vastly improves readability, maintainability, and comprehension.

And as Thomas has pointed out in the comments, it's better when using javascript to place the opening curly brace on the same line as the function declaration in order to prevent unintended semicolon insertion.


2. Descriptive Naming

Yuck

function foo($var, $var2) {
    return $var + $var2;
}

Yes, the example used previously in item four is terrible not only for its syntax but also because the function and variable names don't mean anything.

Preferred

function add_numbers($num1, $num2)
{
    return $num1 + $num2;
}

I don't think this item warrants a Better example. Just keep in mind that the more explicit you can be the better. What happens when you come back to this function in a couple of months? Well, with this example you could probably figure it out quickly, but anything more complicated will benefit greatly. Also, when naming functions, I like to use a verb combined with something that describes either the expected input or the expected output (depending on the application). Of course, this can be improved further by...


1. Commenting / DocBlock

Yuck

function foo($var, $var2) {
    return $var + $var2;
}

I don't think there's anything worse than inheriting code that hasn't been commented. This is a stale cracker. Yeah, you could eat it if you wanted to, but it would suck.

Better

// Add two numbers together
function foo($var, $var2) {
    return $var + $var2;
}

It doesn't matter if nobody else will ever see your code; at least YOU will eventually benefit from taking two seconds and writing a one-line description of what your function does.

Preferred

/**
 * Add two numbers together
 *
 * @param int $num1
 * @param int $num2
 * @return int
 */
function add_numbers($num1, $num2)
{
    return $num1 + $num2;
}

The trend continues here with the Preferred method taking up the most room. But there's no doubt about what this function does. In addition, if you're using an editor that supports DocBlock (I use NetBeans), the description will pop up in a reference window when you start typing the function name somewhere else. That's pretty dandy.

Thomas Hopkins

May 1, 2012

There’s a standard I like to use in [removed] wrapping all my code in a self-invoking function or closure or whatever you want to call them. In the example you give for number 3, those two functions – show_example and do_something_else – both sit in JavaScript’s global namespace: the window object if in a web browser. That means that any other script, whether intended or not, can change or even replace those two functions with something else, be that another function or another value altogether. Self-invoking functions allow you to avoid that.

All you need to do is surround your code like so:
(function () {
  //put code here, e.g.:
  function show_example() {
    // Do stuff
  }

  function do_something_else() {
    // Do more stuff
  }

  $(function(){
      if($(’.some_class’).length) {
        show_example();
      }
      do_something_else();
  });
}());

In the example above, the two functions are local to the closure’s scope and will not be available to other scripts; they won’t be attached to the global window object. You can even use many nested closures to accomplish

JavaScript’s semicolon insertion makes it better to keep braces in the same line as other statements, so in JavaScript

if (varName) {
//more code
}

is preferred over

if (varName)
{ //more code
}

I grant that you don’t run into problems with semicolon insertion in most cases. But they’re pernicious. (In general, though, choosing to put braces in any particular place can spark a holy war.)

Just my two cents. Indentation is probably the one thing in this post that I’m most adamant about. Code without indentation may be great for parsing, but it makes for poor reading.

John Manning

May 2, 2012

Right you are, Thomas. I hadn’t read up on closures before. Typically my js files are small enough to easily avoid naming collisions, but I can see why it’s preferred to limit availability in some situations. I found these articles to be helpful:

http://helephant.com/2008/10/17/javascript-closures/

-and (courtesy Wayback Machine!)-

http://web.archive.org/web/20080209105120/http://blog.morrisjohns.com/javascript_closures_for_dummies

As for semicolon insertion, I suppose I’ve become accustomed to using an editor with syntax highlighting. And most of the time, the closing semicolon is inserted automatically. However, I see that you’re method is a better practice. I’ll update the post.

Thanks :)

Post a Comment