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:
- W3Schools HTML/CSS Style Guide (quick and basic)
- Google HTML/CSS Style Guide (much more extensive)
- W3Schools JavaScript Style Guide (quick and basic)
- Google JavaScript Style Guide (much more extensive)
- PSR-2: PHP Coding Standards
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:
- Indent inside a new block: 4 spaces
- Indent second/subsequent lines of a long/wrapped statement: 4 spaces
- All other indents: add 2 spaces to existing indent (see below)
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:
- Between groups of logically similar statements.
- Above and below a method/function header.
- Documentation that appears above the method/function should have a blank line above, but there should be NO blank line between the documentation and the method/function it documents.
- If you use next-line brace style, the line with the opening brace
can serve as the "blank line" after the function header. e.g.
function foo() { // this can be the blank line
- Between blocks of code (code inside a set of braces).
- Above a comment.
Blank lines should not appear in the following circumstances:
- Between a comment and the statement(s) the comment is documenting.
- Between the first line and second/subsequent lines of a single, long wrapped statement.
In general, a blank space should appear in a code statement in the following circumstances:
- Around an operator (such as ==, =, +, /, new, < or <=, etc.).
An exception that many
programmers use is around the concatenation operator in PHP
(e.g. "Hello, ".userName)
(although many code formatters will add the space, either is fine) - After a comma.
- Before an opening brace if there's something in front of the brace. For example, in a CSS rule, there should be a space between the last selector and the opening brace; in JavaScript or PHP there should be a space between the closing parenthesis and the opening brace, when using end-of-line brace style.
- After a structure keyword such as "if", "else", "while", "for", etc.
Blank spaces should not appear in the following circumstances:
- Between a function/method name and the opening parenthesis.
- After any opening parenthesis and its contents or before any closing parenthesis and its content.
- In the middle of any identifier.
- In front of a comma.
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.
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:
- After a comma.
- Before an operator (i.e. operators should be at the beginning of the next line).
- DO NOT break a line in the middle of a string literal. Close the string's quotes
when you're ready to break the line, then start the new line with the concatenation
operator and continue with the string literal. Here's an example using JavaScript:
document.createTextNode("this is a long string literal that is " + "being displayed over multiple lines of code. This " + "is the proper way to break a long line in the middle of " + "a string literal.");
- Exception: You can't break in the middle of a URI e.g.
<a href="https://www.wow.this.is.a.really/long/long/long/long/long/long/long/long/url/that/is/fake/but/reallyLong.html">Long URL</a>
To code this, just add a hard-return as soon as you encounter a space. Note that you wouldn't put the space after the > before the start of the link text, as this would render an actual space in front of the link text in the browser, which may affect spacing/layout of the rendered result.
- Exception: You can't break in the middle of a URI e.g.
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:
- Next-Line Style: places the opening brace on the next line:
function validateEmail(email) { // .... blah blah }
- End-of-Line Style: places the brace at the end of the line:
function validateEmail(email) { // .... blah blah }
Either style is acceptable. Pick one and stick with it consistently.
- 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:
- Never use unnecessary parentheses. For example:
// parentheses are necessary here: let result = (pointX2 - pointX1) / (pointY2 - pointY1); // none of the parentheses are necessary here: let result = ((pointY * slope) + intercept);
- Don't use unnecessary if statements when a single boolean expression
will do. For example:
if ($result > 0) { $output = true; } else { $output = false; }
should be written as:$output = $result > 0;
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):
- All HTML should be valid.
- All HTML should be accessible (following the techniques discussed in this course).
- All elements, attributes, and attribute values must be in lower-case (except DOCTYPE, which can be either upper- or lower-case).
- The <html> element must include the
lang="en"
attribute. - All documents should specify UTF-8 encoding via <meta charset="utf-8"> (not needed for css since uft-8 is assumed)
- All documents should be declared as using the HTML Living Standard document type via <!DOCTYPE html> or <!doctype html>
- Use HTML elements for their intended purpose e.g. use <h1> for a level-1 heading; to bold and centre text, use a <p> element with appropriate styles to bold and centre.
- Follow the Progressive Enhancement methodology: Keep structure (html), presentation (styles), and functionality (scripts) separate where possible.
- All block and table elements should start on a new line. Examples:
<ul> <li>List Item</li> <li>List Item</li> </ul>
or<table> <tr> <th>Heading</th> <th>Heading</th> </tr> </table>
- All HTML inline elements should always be a child of a block element.
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:
- All css must be valid.
- Declarations inside a rule should be alphabetized. For example:
.main-box { background: #003; border: 1px dashed #000; border-radius: 4px color: #fff; margin: 5px; padding: 2px; }
- Always end each declaration with semi-colon, even the last one in a block.
- Always use end-of-line brace style.
- Each declaration should go on its own line (see alphabetized example above).
- For rules with multiple selectors, each selector goes on its own line. For
Example:
h1, h2, h3 { font-weight: normal; line-height: 1.2; }
- Always add a blank line between rules.
- Use comments to group related rules into sections e.g header rules, footer rules, etc.
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:
- All script files should include
"use strict";
- Always declare variables with the
let
keyword and constants with theconst
keyword. - Use unobtrusive JavaScript only.
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:
- Always use next-line brace style.
- if structures: the closing brace of the if-block of an else/elseif must
be on the same line as the else/elseif keyword, as should be the opening
brace of the else/elseif block; elseif should be one word, not two.
Example:
if ($result > 50) { echo "Over 50"; } elseif ($result > 20) { echo "Between 20 and 50"; } elseif ($result > 0) { echo "20 and under"; } else { echo "Invalid."; }
- In a do-while loop, the while keyword and condition follows the closing
brace on the same line i.e
} while ($result <= 0);
- No more than one statement per line. For example:
// incorrect: $result = Math.pow($base, $exp); echo $result; // correct: $result = Math.pow($base, $exp); echo $result;
- PHP keywords such as true, false, null should always be in lower-case.