Chapter 39. Coding Guidelines

Whether you're working on a project by yourself or with a group of other developers, it's very important that you follow a set of guidelines as you write code. Following guidelines promotes code quality, making it easier for you and others to find bugs, read, and maintain. The heart of most sets of guidelines is code conventions inherent to the programming language. For example, when you were introduced to variables and identifiers in Lesson 2, you were taught how identifiers should follow the code conventions already in use by the language itself.

Aside from naming identifiers, JavaScript developers follow a varying set of guidelines, usually based on conventions, to make their code easier to read and maintain. Let's look at some of them.

USE WHITESPACE

Whitespace, while not actually code, is one of the most important pieces of a programming language. It allows you to visually organize your code into readable and maintainable chunks of text. Without whitespace code would be a jumbled mess of text. Look at the following code for an example:

function doSomethingUseless(num){if(num===1){num=num+1;
doSomethingUseless(1);}
else{num=num*2;for(var i=0;i<num;i++){
num--;}
return num;
}
}

This code is difficult to read. By scanning it you can see that it's a function with some decisions and loops, but the lack of whitespace makes it difficult to discern what the code actually does. So let's add some whitespace to make it more readable:

function doSomethingUseless(num) {
    if (num === 1) {
num = num + 1;
        doSomethingUseless(num);
    } else {
        num = num * 2;
        for (var i = 0; i < num; i++) {
            num--;
        }
        return num;
    }
}

To visually organize your code, follow these guidelines:

  • Put each statement on its own line.

  • Organize code blocks by doing the following:

    • Put the opening curly brace ({)at the end of the line that begins the code block.

    • Put the closing curly brace (}) at the beginning of a new line. It should be indented to align with the statement that contains the opening curly brace.

    • Indent each line of code so that you can see what lines of code are contained within a particular code block.

  • Add a single space between values and operators. The code 2+2 is easier to read as 2 + 2.

VARIABLE DECLARATIONS

Something else that makes code easier to read and maintain is declaring all variables at the beginning of a function (using the var keyword, of course). Consider the following code as an example:

function nothingSpecial(value) {
    var multiplier = 2;
    var result = value;

    for (var i = 0; i < value; i++) {
        result = result * 2 + num;
    }

    return result;
}

Placing variables declarations at the top of a function also has the side effect of pointing out possible errors. For example, this code uses a variable called num inside the for loop. It's obviously important to the nothingSpecial() function because it's used in the calculation of result.

So is num supposed to be global, or is it supposed to be a local variable? Can you count on its having a value before trying to use it in a calculation? By declaring variables at the top of a function you can catch little things like the num variable since you know what variables to expect in the function. Also remember that JavaScript has no block-level scope. Placing variable declarations at the beginning of a function makes that fact explicit.

Note

Variables serving as loop counters are an exception. Typically, they're declared with the loop they count.

AVOID THE GLOBAL SCOPE

The previous section posed a valid question regarding a variable that was not declared within a function. Is it global? One of JavaScript's faults is its dependency on the global scope. JavaScript assumes undeclared variables are global, and that can lead to undesired results in your application. So it's best to avoid the global scope.

Avoiding the global scope is also advantageous because it helps you avoid naming conflicts (that is, having more than one variable or function with the same name). As you develop more and more applications you may find yourself using code written by someone else, such as the code in the popular jQuery library. The more code written by a third party you add to a project, the greater the chance of a naming conflict. While avoiding the global scope entirely is next to impossible, you can minimize naming conflicts by keeping as much of your code out of the global scope as possible. You'll learn exactly how to do this in Lesson 42.

USE LITERALS

The performance of your web application is linked to how fast it downloads to the user's browser. Obviously, larger files take more time to download. With broadband connections becoming more and more the norm, it may seem that file size doesn't matter. After all, a 50KB file takes .05 seconds to download on a 1MB/s line, but it can add up. So cutting out unnecessary characters not only makes typing easier, but also trims down the size of your code.

Perhaps the best way to type less is to use literal notation when creating objects and arrays instead of calling their constructors. Remember, object literals use curly braces ({}) and array literals use square brackets ([]). For example, the following code creates an object with three properties, one of which is an array, using the Object and Array constructors:

var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.friends = new Array();
person.friends[0] ="Jim";
person.friends[1] = "Jane";
person.friends[2] = "Bartholomew";

That's a lot of typing to create one person object: 203 bytes worth of characters. Contrast that with the following code:

var person = {
    firstName : "John",
    lastName : "Doe",
friends : [
        "Jim",
        "Jane",
        "Bartholomew"
    ]
};

This code uses literal notation to create the same person object. Even though it has two more lines than the previous code, it's less typing and weighs in at 146 bytes. That's a significant decrease in size, and the size difference would only grow as more properties or array elements were added.

Many professionals use a tool called JSLint (http://www.jslint.com/), written by Douglas Crockford, to analyze code and check its quality. The guidelines mentioned in this lesson are just a few of the items JSLint looks at, and future lessons touch on other items scrutinized by JSLint.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.194