Coding Standards for SYST10199

This document contains a few of the common standards and conventions used in web development and web programming. You should follow these standards for this course. Marks are allotted for following proper coding standards/style/conventions on every assignment.

A more extensive list and description of web programming standards is available at the following web links:

Naming Conventions for Identifiers

Naming conventions for identifiers in HTML (e.g. id or name attribute values), CSS (e.g. class/id names), JavaScript, and PHP should be followed to improve readability. Some languages include special prefixes that are prepended to variable and object names to identify the types of data or object.

Regardless of language and type of identifier, all identifiers must be self-documenting (you can tell exactly what the identifier is for by reading its name). For example, custFirstName is clearly a customer's first name and validateEmail obviously performs data validation on an email address. Names like single letters (x, c, etc), or names that are meaningless (count1, temp, f23) should not be used (one exception is that we often use a single letter such as i in a for-loop).

The following table outlines naming conventions for various types of identifers in the web programming technologies covered in this course:

  Identifier type
Language selector (e.g. in class="" or id="") variable method/function class (oop) constants
HTML all lower-case, hyphens to separate words n/a n/a n/a n/a
CSS all lower-case, hyphens to separate words n/a n/a n/a n/a
JavaScript n/a start with lower-case + camel-case start with lower-case + camel-case start with upper-case + camel-case all upper-case; separate words with underscore (_)
PHP n/a start with $lower-case + camel-case start with lower-case + camel-case start with upper-case + camel-case all upper-case; separate words with underscore (_)

Indentation and Spacing

Indentation and spacing keeps code readable, especially when there are nested structures involved. For example, if you have a series of <section> tags and each has a set of <p> tags, proper indentation will make it easier to read and edit your document. Similarly, a JavaScript or PHP program with nested if's and loops is easier to follow and maintain when it's indented properly.

Size of Indents

The size of indents varies. The table below outlines the size of indents in the various web technologies used in this course:

Language Indent Size (# of spaces)
HTML 2
CSS 2
JavaScript 2 or 4*
PHP 4

Note that indents should always be actual spaces, not tabs. You can still press the Tab key to indent, since it is now a function of most modern editors to convert tabs to spaces automatically. But check your editor's settings if you're not sure. If your editor doesn't convert tabs to spaces, your code will not format properly in other editors (i.e. the teacher's editor).

When nesting structures, always add one indentation level per nesting level. Examples:

HTML Example:

<body>
  <section>
    <p>Some content.</p>
  </section>
        
  <section>
    <p>Some content.</p>
    <aside>Some more content.</aside>
    <p>Some content.</p>
  </section>
</body>

PHP Example:

function printGrades($myGrades) {

    echo "<h1>My Grades:</h1><p>";

    foreach($myGrades as $course => $mark) {

        echo "$course: $mark";
        if ($mark < 50) {
            echo " (fail)";
        }
        echo "<br>";
    }
    echo "</p>\n";
}

*Indenting in JavaScript

You should follow these basic rules to start with:

JavaScript has some additional rules about indenting certain kinds of statements that break up over multiple lines. For example, when initializing an Array over multiple lines, the second and subsequent statements are indented only 2 spaces, instead of the regular 4 spaces. Additional information and rules can be found at Google JavaScript Style Guide.

Spacing

There are two categories of spacing: blank lines in code and blank space in code statements.

In general, there should be a blank line in the following circumstances:

Blank lines should not appear in the following circumstances:

In general, a blank space should appear in a code statement in the following circumstances:

Blank spaces should not appear in the following circumstances:

Additionally, each language covered in this course has some specific rules regarding blank lines and spaces:

Language Blank Lines Blank Space
HTML no specific rules beyond industry standard - there should never be a blank space around the assignment operator when assigning a value to an attribute e.g. <a href="images/pic.png" alt="a picture"> is correct.
CSS - between rules, i.e there should be a blank line after the closing brace of a rule and the start of the next rule - after the colon that follows a selector e.g. font-size:150%; is incorrect because there should be a space after the :
PHP - after a (or group of) use statements
- after a namespace statement
no specific rules beyond industry standard

Line Length

Industry standard for most languages state that the length of a line should not exceed 80 characters.

If a statement is longer than 80 characters, break that statement up over multiple lines with a hard-return. The second and subsequent lines must be indented.

Note
A hard-return is inserted when you press the ENTER key on your keyboard. A soft-return occurs when your document's contents word-wrap. Hard-returns and soft-returns are different character sequences. Hard returns will be saved with a document, so if someone else views your code, they see the hard returns exactly where you put them. Soft returns may not appear exactly the same: if someone has a smaller screen width or a larger font, the words will wrap in different places.

If a language supports end-of-line comments, use them only if the total number of characters in the line, including the comment, is 80 characters or less. If your comment makes the line longer than 80 characters, place the comment above the statement, instead.

Most editors allow you to add a margin marker at a specific column to help you see where the 80 character mark is.

Breaking Long Lines

When breaking a long statement into multiple lines of code, you must always indent the second and subsequent lines. See the Indentation and Spacing standards for information on the size of an indent for each language covered in this course.

In most languages there are rules regarding where you can place a hard-return in a long line. In general, the following rules apply:

Braces

Braces are used in CSS, JavaScript, and PHP to identify blocks. In CSS, a block defines a style rule; in JavaScript and PHP, blocks are used to define classes, methods/functions, and to contain code for structures such as loops, selections, exception handlers, collections, etc.

A left brace (or opening brace) { starts a block and a right brace (or closing brace) } ends a block.

Examples of blocks:

h2 {
  font: bold 1.3em sans-serif;
  color: #039;
  border-bottom: 1px solid #039;
}
function printArray(array) {
    // code to print an array
}

if (val - 2 > 0) {
    // if-block
} else {
    // else-block
}

Brace Style

Brace style defines where you decide to put the opening brace of a block. There are two standard styles:

Either style is acceptable. Pick one and stick with it consistently.

Exceptions:
  • CSS always uses end-of-line brace style.
  • PHP always uses next-line brace style for classes and methods/functions, but uses end-of-line brace style for control structures (ifs, loops, etc) and with the try/catch structure.

Documentation

Documentation should be concise, complete, and written in your own words. Use proper spelling!! There's nothing less professional in your code than bad spelling in your documentation! :P

DO NOT document the ends of long lines like this:

document.createTextNode("The interest is " + investment * Math.pow((1 + rate)/100, years));  // calculates and displays the interest earned

Those kinds of statements are almost impossible to read in any standard editor!

It's better to place the comment above the line, like this:

// calculates and displays the interest earned
document.createTextNode("The interest is " + investment * Math.pow((1 + rate)/100, years));

If you want to use end-of-line comments, use them on short lines, such as variable/constant declarations:

let investment = 1000;  // investment amount
let years = 10;  // number of years
let rate = .025;  // interest rate

If an end-of-line comment causes the line to be longer than 80 characters (including the comment), place the comment above the line instead.

For programming languages, document each statement or related groups of statements by describing how the code applies to the logic of your program or why it's written this way. You can use multi-line or single-line comments, whichever you're most comfortable with.

Examples

let images = [];  // to hold the file names of dice images

// preload the array of 6 dice images
for (let i = 0; i < 6; i++) {
    // each file is dieN.jpg where N is die number
    images[i] = "images/die" + (i + 1) + ".jpg";
}

/*
  rollDice() function is called whenever the user clicks the "Roll" button
  on the web page.  This generates 2 random numbers to represent the two
  dice rolls, then updates the screen to show the values rolled with the 
  corresponding dice images.
*/
function rollDice() {

    // roll the 2 dice by generating 2 random #s from 1 to 6
    let d1 = parseInt(Math.random() * 6 + 1);
    let d2 = parseInt(Math.random() * 6 + 1);

    // divs with dice images
    let divDie1 = document.getElementById("die1Msg");
    let divDie2 = document.getElementById("die2Msg");

    // update the captions below the images of the dice
    divDie1.textContent = "You rolled a " + d1;
    divDie2.textContent = "You rolled a " + d2;

    // show the dice images for the 2 values rolled
    divDie1.querySelector("img").src = images[d1-1];
    divDie2.querySelector("img").src = images[d2-1];

    // show the border around the dice image divs
    divDie1.className = "dieContainerBorder";
    divDie2.className = "dieContainerBorder";
}

For HTML, documentation describes the various sections/areas of a page or explains other important elements (e.g. why a script is called in the body of a document).

An HTML Example:

<!-- header section of page -->
<header>
  <h1>SPCA Emergency Personnel</h1>

  <h2>Log In to Handle Calls</h2>

  <img class="header-img" src="images/spcaHeader.png" alt="Hamilton SPCA Header">
</header>

<!-- login form that validates inputs on submit -->
<form action="login.php" method="post" name="loginForm">

  <p>
    <label for="txtUser">User Name: 
      <input type="text" id="txtUser" name="txtUser" required>
    </label>
  </p>

  <p>
    <label for="txtPass">
      <input type="password" id="txtPass" name="txtPass" required>
    </label>
  </p>

  <p>
    <input type="submit"> 
    <input type="reset">
  </p>
</form>

<!-- footer section of page -->
<footer>
  <address>
    <!-- display copyright notice from script -->
    <script type="text/javascript" src="js/copyright.js"></script>
  </address>
</footer>

Miscellaneous Standards and Conventions

The following standards and conventions don't fit into any of the above categories:

HTML Standards

In addition to the general standards and conventions already mentioned, the following apply to HTML and should be used in all submissions in this course (note that many of these things are considered part of valid HTML, anyway):

CSS Standards

In addition to the general standards and conventions already mentioned, the following apply to CSS and should be used in all submissions in this course:

JavaScript Standards

In addition to the general standards and conventions already mentioned, you should be following ECMA-262 standards for JavaScript, and code in Strict Mode. This means the following items apply to JavaScript and should be used in all submissions in this course:

PHP Standards

In addition to the general standards and conventions already mentioned, the following apply to PHP and should be used in all submissions in this course: