Simpleview Code Guide

SV Code Guide

Standards for developing flexible, durable, and sustainable HTML, CSS and JavaScript.

Golden rule

Enforce these, or your own, agreed upon guidelines at all times. Small or large, call out what's incorrect.

Every line of code should appear to be written by a single person, no matter the number of contributors.

HTML

Syntax

  • Use hard tabs with four spaces.
  • Nested elements should be indented once (1 tab).
  • Always use double quotes, never single quotes, on attributes.
  • Don't include a trailing slash in self-closing elements—the HTML5 spec says they're optional.
  • Don’t omit optional closing tags (e.g. </li> or </body>).
<!DOCTYPE html>
<html>
    <head>
        <title>Page title</title>
    </head>
    <body>
        <img src="images/company-logo.png" alt="Company">
        <h1 class="hello-world">Hello, world!</h1>
    </body>
</html>

HTML5 doctype

Enforce standards mode and more consistent rendering in every browser possible with this simple doctype at the beginning of every HTML page.

<!DOCTYPE html>
<html>
    <head>
    </head>
</html>

Language attribute

From the HTML5 spec:

Authors are encouraged to specify a lang attribute on the root html element, giving the document's language. This aids speech synthesis tools to determine what pronunciations to use, translation tools to determine what rules to use, and so forth.

Read more about the lang attribute in the spec.

Head to Sitepoint for a list of language codes.

<html lang="en-us">
    <!-- ... -->
</html>

IE compatibility mode

Internet Explorer supports the use of a document compatibility <meta> tag to specify what version of IE the page should be rendered as. Unless circumstances require otherwise, it's most useful to instruct IE to use the latest supported mode with edge mode.

For more information, read this awesome Stack Overflow article.

<meta http-equiv="X-UA-Compatible" content="IE=Edge">

Character encoding

Quickly and easily ensure proper rendering of your content by declaring an explicit character encoding. When doing so, you may avoid using character entities in your HTML, provided their encoding matches that of the document (generally UTF-8).

<head>
    <meta charset="UTF-8">
</head>

CSS and JavaScript includes

Per HTML5 spec, typically there is no need to specify a type when including CSS and JavaScript files as text/css and text/javascript are their respective defaults.

HTML5 spec links

<!-- External CSS -->
<link rel="stylesheet" href="code-guide.css">

<!-- In-document CSS -->
<style>
    /* ... */
</style>

<!-- JavaScript -->
<script src="code-guide.js"></script>

Practicality over purity

Strive to maintain HTML standards and semantics, but not at the expense of practicality. Use the least amount of markup with the fewest intricacies whenever possible.

Attribute order

HTML attributes should come in this general order for easier reading of code.

  • class, id, name
  • src, for, type, href, value
  • title, alt
  • role, aria-*
  • data-*

Classes make for great reusable components, so they come first. Ids are more specific and should be used sparingly (e.g., for in-page bookmarks), so they come second.

<a class="..." id="..." href="#" data-toggle="modal">
    Example link
</a>

<input class="form-control" type="text">

<img src="..." alt="...">

Boolean attributes

A boolean attribute is one that needs no declared value. XHTML required you to declare a value, but HTML5 has no such requirement.

For further reading, consult the WhatWG section on boolean attributes:

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If you must include the attribute's value, and you don't need to, follow this WhatWG guideline:

If the attribute is present, its value must either be the empty string or [...] the attribute's canonical name, with no leading or trailing whitespace.

In short, don't add a value.

<input type="text" disabled>

<input type="checkbox" value="1" checked>

<select>
    <option value="1" selected>1</option>
</select>

Reducing markup

Whenever possible, avoid superfluous parent elements when writing HTML. Many times this requires iteration and refactoring, but produces less HTML. Take the following example:

<!-- Not so great -->
<span class="avatar">
    <img src="...">
</span>

<!-- Better -->
<img class="avatar" src="...">

JavaScript generated markup

Writing markup in a JavaScript file makes the content harder to find, harder to edit, and less performant. Avoid it whenever possible.

CSS

Syntax

  • Use hard tabs with four spaces.
  • When grouping selectors, keep individual selectors to a single line.
  • Include one space before the opening brace of declaration blocks for legibility.
  • Place closing braces of declaration blocks on a new line.
  • Include one space after : for each declaration.
  • Each declaration should appear on its own line for more accurate error reporting.
  • End all declarations with a semi-colon. The last declaration's is optional, but your code is more error prone without it.
  • Comma-separated property values should include a space after each comma (e.g., box-shadow).
  • Always prefix property values or color parameters with a leading zero (e.g., 0.5 instead of .5 and -0.5px instead of -.5px).
  • Lowercase all hex values, e.g., #fff. Lowercase letters are much easier to discern when scanning a document as they tend to have more unique shapes.
  • Use shorthand hex values where available, e.g., #fff instead of #ffffff.
  • Quote attribute values in selectors, e.g., input[type="text"]. They’re only optional in some cases, and it’s a good practice for consistency.
  • Avoid specifying units for zero values, e.g., margin: 0; instead of margin: 0px;.

Questions on the terms used here? See the syntax section of the Cascading Style Sheets article on Wikipedia.

/* Bad CSS */
.selector, .selector-secondary, .selector[type=text] {
    padding:15px;
    margin:0px 0px 15px;
    background-color:rgba(0,0,0,.5);
    box-shadow:0px 1px 2px #CCC,inset 0 1px 0 #FFFFFF
}

/* Good CSS */
.selector,
.selector-secondary,
.selector[type="text"] {
    padding: 15px;
    margin-bottom: 15px;
    background-color: rgba(0, 0, 0, 0.5);
    box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff;
}

Declaration order

Related property declarations should be grouped together following the order:

  1. Positioning
  2. Box model
  3. Typographic
  4. Visual

Positioning comes first because it can remove an element from the normal flow of the document and override box model related styles. The box model comes next as it dictates a component's dimensions and placement.

Everything else takes place inside the component or without impacting the previous two sections, and thus they come last.

For a complete list of properties and their order, please see Recess.

.declaration-order {
    /* Positioning */
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 100;

    /* Box-model */
    display: block;
    float: right;
    width: 100px;
    height: 100px;

    /* Typography */
    font: normal 13px "Helvetica Neue", sans-serif;
    line-height: 1.5;
    color: #333;
    text-align: center;

    /* Visual */
    background-color: #f5f5f5;
    border: 1px solid #e5e5e5;
    border-radius: 3px;

    /* Misc */
    opacity: 1;
}

Single declarations

In instances where a rule set includes only one declaration, consider removing line breaks for readability and faster editing. Any rule set with multiple declarations should be split to separate lines.

The key factor here is error detection—e.g., a CSS validator stating you have a syntax error on Line 183. With a single declaration, there's no missing it. With multiple declarations, separate lines is a must for your sanity.

/* Single declarations on one line */
.span1 { width: 60px; }
.span2 { width: 140px; }
.span3 { width: 220px; }

/* Multiple declarations, one per line */
.sprite {
    display: inline-block;
    width: 16px;
    height: 15px;
    background-image: url(../img/sprite.png);
}
.icon           { background-position: 0 0; }
.icon-home      { background-position: 0 -20px; }
.icon-account   { background-position: 0 -40px; }

Media query placement

Place media queries as close to their relevant rule sets whenever possible. Don't bundle them all in a separate stylesheet or at the end of the document. Doing so only makes it easier for folks to miss them in the future. Here's a typical setup.

.element { ... }
.element-avatar { ... }
.element-selected { ... }

@media (min-width: 480px) {
    .element { ...}
    .element-avatar { ... }
    .element-selected { ... }
}

Prefixed properties

When using vendor prefixed properties, indent each property such that the declaration's value lines up vertically for easy multi-line editing.

In Sublime Text 2, use Selection → Add Previous Line (ctrl + alt + ↑) and Selection → Add Next Line (ctrl + alt + ↓). In Atom, user Selections → Add Selection Above (alt + ctrl + ↑) and Selection → Add Selection Below (alt + ctrl + ↓).

/* Prefixed properties */
.selector {
    -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
}

Shorthand notation

Strive to limit use of shorthand declarations to instances where you must explicitly set all the available values. Common overused shorthand properties include:

  • padding
  • margin
  • font
  • background
  • border
  • border-radius

Often times we don't need to set all the values a shorthand property represents. For example, HTML headings only set top and bottom margin, so when necessary, only override those two values. Excessive use of shorthand properties often leads to sloppier code with unnecessary overrides and unintended side effects.

The Mozilla Developer Network has a great article on shorthand properties for those unfamiliar with notation and behavior.

/* Bad example */
.element {
    margin: 0 0 10px;
    background: red;
    background: url("image.jpg");
    border-radius: 3px 3px 0 0;
}

/* Good example */
.element {
    margin-bottom: 10px;
    background-color: red;
    background-image: url("image.jpg");
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
}

Comments

Code is written and maintained by people. Ensure your code is descriptive, well commented, and approachable by others. Great code comments convey context or purpose. Do not simply reiterate a component or class name.

Be sure to write in complete sentences for larger comments and succinct phrases for general notes.

/* Bad example */
/* Modal header */
.modal-header {
    ...
}

/* Good example */
/* Wrapping element for .modal-title and .modal-close */
.modal-header {
    ...
}

Class names

  • Keep classes lowercase and use dashes (not underscores or camelCase). Dashes serve as natural breaks in related class (e.g., .btn and .btn-danger).
  • Avoid excessive and arbitrary shorthand notation. .btn is useful for button, but .s doesn't mean anything.
  • Keep classes as short and succinct as possible.
  • Use meaningful names; use structural or purposeful names over presentational.
  • Prefix classes based on the closest parent or base class.

It's also useful to apply many of these same rules when creating Sass and Less variable names.

/* Bad example */
.t { ... }
.red { ... }
.header { ... }

/* Good example */
.tweet { ... }
.important { ... }
.tweet-header { ... }

Selectors

  • Use classes over generic element tag for optimum rendering performance.
  • Avoid using several attribute selectors (e.g., [class^="..."]) on commonly occuring components. Browser performance is known to be impacted by these.
  • Keep selectors short and strive to limit the number of elements in each selector to three.
  • Scope classes to the closest parent only when necessary (e.g., when not using prefixed classes).

Additional reading:

/* Bad example */
span { ... }
.page-container #stream .stream-item .tweet .tweet-header .username { ... }
.avatar { ... }

/* Good example */
.avatar { ... }
.tweet-header .username { ... }
.tweet .avatar { ... }

Organization

  • Organize sections of code by component.
  • Develop a consistent commenting hierarchy.
  • Use consistent white space to your advantage when separating sections of code for scanning larger documents.
  • When using multiple CSS files, break them down by component instead of page. Pages can be rearranged and components moved.
/*
 * Component section heading
 */

.element { ... }


/*
 * Component section heading
 *
 * Sometimes you need to include optional context for the entire component. Do that up here if it's important enough.
 */

.element { ... }

/* Contextual sub-component or modifer */
.element-heading { ... }

JavaScript

Syntax

  • Use hard tabs with four spaces.
  • Remove all trailing white space.
  • Always end you statements with a semicolon.
  • Your opening braces go on the same line as the statement.
  • Else opening should be on the same line as the if closing brace.
  • If statements can be single line if they have a single return.
  • Declare one variable per var statement, it makes it easier to re-order the lines. However, ignore Crockford when it comes to declaring variables deeper inside a function, just put the declarations wherever they make sense.
// Use 4 space hard tabs for indents
// Bad example
if (bar === foo) {
    /* ... */
}

// Good example
if (bar === foo) {
    /* ... */
}


// End your statements with a semicolon
// Bad example
console.log('I done goofed')

// Good example
console.log('Hello, world!');

// Opening braces go on the same lines
// Bad example
if (bar === foo)
{
    // This is madness
    var bat = bar + foo;
}

// Good example
if (bar === foo) {
    var bat = bar + foo;
} else {
    var bin = bar * foo;
}


// Declare one variable per statement
// Bad example
var keys = ['foo', 'bar'],
    values = [23, 42],
    object = {},
    key;

while (keys.length) {
    key = keys.pop();
    object[key] = values.pop();
}

// Good example
var keys   = ['foo', 'bar'];
var values = [23, 42];

var object = {};
while (keys.length) {
    var key = keys.pop();
    object[key] = values.pop();
}

Naming Conventions

  • Variables, properties and function names should use lowerCamelCase. They should also be descriptive. Single character variables and uncommon abbreviations should generally be avoided.
  • Class names should be capitalized using UpperCamelCase.
  • Constants should be declared as regular variables or static class properties, using all uppercase letters.
// Variables, Properties and Function names
// Bad example
var admin_user = db.query('SELECT * FROM users ...');

// Good example
var adminUser = db.query('SELECT * FROM users ...');


// Class names
// Bad example
function bank_Account() {
}

// Good example
function BankAccount() {
}


// Constants
// Bad example
const SECOND = 1 * 1000;

function File() {
}
File.fullPermissions = 0777;

// Good example
var SECOND = 1 * 1000;

function File() {
}
File.FULL_PERMISSIONS = 0777;

Variables

Put short declarations on a single line. Only quote keys when your interpreter complains.

// Bad example
var a = [
    'hello', 'world'
];
var b = {"good": 'code'
        , is generally: 'pretty'
        };

// Good example
var a = ['hello', 'world'];
var b = {
    good: 'code',
    'is generally': 'pretty'
};

Conditionals

Use the === operator

Use the triple equality operator as it will work just as expected.


Use descriptive conditions

Any non-trivial conditions should be assigned to a descriptively named variable or function.

// Use the === operator
// Bad example
var a = 0;
if (a == '') {
    console.log('losing');
}

// Good example
var a = 0;
if (a !== '') {
    console.log('winning');
}

// User descriptive conditions
// Bad example
if (password.length >= 4 && /^(?=.*\d).{4,}$/.test(password)) {
    console.log('losing');
}

// Good example
var isValidPassword = password.length >= 4 && /^(?=.*\d).{4,}$/.test(password);

if (isValidPassword) {
    console.log('winning');
}

Functions

Write small functions

Keep your functions short. A good function fits on a slide that the people in the last row of a big room can comfortably read. So don't count on them having perfect vision and limit yourself to ~15 lines of code per function.


Return early from functions

To avoid deep nesting of if-statements, always return a function's value as early as possible.



Limit nested closures

There will always be times when you'll need to nest your closures, but limit the depth to ~3 deep otherwise your code can become unreadable and hard to maintain.


Method chaining

One method per line should be used if you want to chain methods.

You should also indent these methods so it's easier to tell they are part of the same chain.

// Return early from functions
// Bad example
function isPercentage(val) {
    if (val >= 0) {
        if (val < 100) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

// Better example
function isPercentage(val) {
    if (val < 0) {
        return false;
    }

    if (val > 100) {
        return false;
    }

    return true;
}

// Even better example
function isPercentage(val) {
    var isInRange = (val >= 0 && val <= 100);
    return isInRange;
}


// Limit nested closures
// Bad example
setTimeout(function() {
    client.connect(function() {
        widget.on('init', function() {
            $(this).find('[data-widget-items]').each(function() {
                console.log('losing');
            });
        });
    });
}, 1000);

// Better example
setTimeout(function() {
    client.connect(initWidget);
}, 1000);

function initWidget() {
    widget.on('init', function() {
        $(this).find('[data-widget-items]').each(function() {
            console.log('winning');
        });
    });
}

// Method chaining
// Bad example
User
.findOne({ name: 'foo' })
.populate('bar')
.exec(function(err, user) {
    return true;
});

User.findOne({ name: 'foo' })
    .populate('bar')
    .exec(function(err, user) {
        return true;
    });

User.findOne({ name: 'foo' }).populate('bar')
.exec(function(err, user) {
    return true;
});

User.findOne({ name: 'foo' }).populate('bar')
    .exec(function(err, user) {
        return true;
    });

// Good example
User
    .findOne({ name: 'foo' })
    .populate('bar')
    .exec(function(err, user) {
        return true;
    });

Comments

Try to write comments that explain higher level mechanisms or clarify difficult segments of your code. Don't use comments to restate trivial things.

// Bad example
// Execute a regex
var matches = item.match(/ID_([^\n]+)=([^\n]+)/);

// Usage: loadUser(5, function() { ... })
function loadUser(id, cb) {
	// ...
}

// Check if the session is valid
var isSessionValid = (session.expires < Date.now());
// If the session is valid
if (isSessionValid) {
    // ...
}

// Good example
// 'ID_SOMETHING=VALUE' -> ['ID_SOMETHING=VALUE', 'SOMETHING', 'VALUE']
var matches = item.match(/ID_([^\n]+)=([^\n]+)/));

// This function has a nasty side effect where a failure to increment a
// redis counter used for statistics will cause an exception. This needs
// to be fixed in a later iteration.
function loadUser(id, cb) {
    // ...
}

var isSessionValid = (session.expires < Date.now());
if (isSessionValid) {
    // ...
}

Miscellaneous

Object.freeze, Object.preventExtensions, Object.seal, with, eval

Crazy shit that you will probably never need. Stay away from it.


Requires At Top

Always put requires at top of file to clearly illustrate a file's dependencies. Besides giving an overview for others at a quick glance of dependencies and possible memory impact, it allows one to determine if they need a package.json file should they choose to use the file elsewhere.


Do not extend built-in prototypes

Do not extend the prototype of native JavaScript objects. Your future self will be forever grateful.

// Do not extend built-in prototypes
// Bad example
Array.prototype.empty = function() {
    return !this.length;
}

var a = [];
if (a.empty()) {
    console.log('losing');
}

// Good example
var a = [];
if (!a.length) {
    console.log('winning');
}

jQuery syntax

Always define a root node for every widget based off of the . This allows us to limit the size of the node tree when use functions like .find() which will improve performance. This will also help restrict any interactions, functions and listeners you define to the specific instance of the widget. Otherwise, other widgets or multiples of the same widget may trigger your code to run.

<!-- Bad example -->
<div class="widget">
    <div class="widget-inner hide">
        <div class="title">Hello, world!</div>
        <div class="description">
            <p>This is a basic example.</p>
        </div>
    </div>
    <button class="widget-button">Show</button>
</div>

<script>
    $('.widget-button').on('click', function() {
        $('.widget-inner').toggleClass('hide');
    });
</script>

<!-- Good example -->
<div class="widget" data-widget="">
    <div class="widget-inner hide">
        <div class="title">Hello, world!</div>
        <div class="description">
            <p>This is a basic example.</p>
        </div>
    </div>
    <button class="widget-button" data-widget-toggle>Show</button>
</div>

<script>
    var root = $('[data-widget=""]');
    root
        .find('[data-widget-toggle]')
        .on('click', function() {
            root
                .find('.widget-inner')
                .toggleClass('hide');
        });
</script>

Avoid using class or id selectors

This helps keep a strict separation between structure and functionality. With this, an element can be completely restyled with an entire new set of classes and ids without any loss of functionality.

<!-- Bad example -->
<div class="item" id="item1" data-item>
    <p class="description">Hello, world!</p>
</div>

<script>
    var root = $('.item#item1');
    root
        .find('.description')
        .addClass('subheader');
</script>

<!-- Good example -->
<div class="item" id="item1" data-item="">
    <p class="description">Hello, world!</p>
</div>

<script>
    var root = $('[data-item=""]');
    root
        .find('.description')
        .addClass('subheader');
</script>

Cache your selectors

If you’re going to use a selector more than once, you should store it in a variable. Not only does it make the code easier to read, but it also improves performance since jQuery no longer has to traverse the DOM to find matching nodes.

// Bad example
var root = $('[data-widget=""]');

root
    .find('.slider')
    .on('init', function() { /*...*/ });
root
    .find('.slider')
    .slick({ /*...*/ });

// Good example
var root = $('[data-widget=""]');
var slider = root.find('.slider');

slider.on('init', function() { /*...*/ });
slider.slick({ /*...*/ });

Async/Await Guidelines

In order to effectively use async/await, you need to understand Promises, callbacks, and async/await. The following are some good resources for the basics.

Async/Await gives us the capability to utilize a synchronous programming style, but make asynchronous calls. There are numerous advantages to this style of programming. It avoids the pyramid of doom. It largely eliminates the need for 3rd party flow control libraries, such as async, flowly, co, bluebird. When done properly, it also eliminates the need for Node's flawed domain package.

Basic Tips:

  • Tip 1: The return of an async function is always a Promise, always. If the function text returns any non-Promise, it will be wrapped in a Promise for you.
  • Tip 2: An async function returns synchronously, it's Promise returns asynchronously. This occurs if you are not using await on the async function.
  • Tip 3: A thrown error in a async function, will be caught and wrapped as-if Promise.reject(err) was performed.
  • Tip 4: While inside an async function, if you ever bounce off the event loop, which means executing async code of any kind whether a setTimeout or any other node-style error-first callback without utilizing await, you must Promise wrap it to avoid un-catchable errors.
  • Tip 5: util.promisify() is the preferred method for promisifying functions within Node since it's part of Node core.
  • Tip 6: You can only utilize await within an async function.
  • Tip 7: If you utilize an async function in conjunction with the async library, then it no longer recieves a cb and your function can simply return a result, or return a Promise. This behavior is not available in flowly, it assumes you will still cb the response.
  • Tip 8: A Promise begins execution the moment it is new'd. It does not wait until an await or then to execute. Sometimes this can cause surprising results.
// Tip 1:
// "yes" will be wrapped in a Promise, by javascript
var foo = async function() {
	return "yes";
}

// note foo() is exec'd without await, this is perfectly valid, but it is a Promise
var t = foo();
console.log(t instanceof Promise, t === "yes"); // true, false
var t = await foo();
console.log(t instanceof Promise, t === "yes"); // false, true

// Tip 2:
var foo = async function() {
	var rec = await someDbQuery({ recid : 5 });
	
	console.log("rec", rec);
	
	return rec.title;
}

var t = foo();
// this log will occur BEFORE the "rec" log above because we did not await on foo() and foo() will return synchronously, but it's promise will resolve async
console.log("after");

// Tip 3:
var foo = async function(arg1) {
	if (typeof arg1 !== "string") { throw new Error("arg1 must be a string"); }
	return "yay, it's a string";
}

// the throw error above will be automatically caught by the promise .catch()
foo(1).catch(function(e) {
	console.log("caught it!");
});

// if we want to catch via await we need to
try {
	var t = await foo(1);
} catch(e) {
	console.log("caught it"); // will log
}

// Tip 4: Handling errors
// wrong: went off the event loop, without handling errors properly
var foo = async function() {
	// bounces off the event loop
	fs.readFile("/tmp/someFile.txt", function(err, result) {
		if (err) { throw err; } // this is an uncatchable error and cannot be try/catch'd
		
		return resolve(result);
	});
}

// right: utilizing a promise
var foo = async function() {
	return new Promise(function(resolve, reject) {
		fs.readFile("/tmp/someFile.txt", function(err, result) {
			if (err) { return reject(err); } // this is catchable by our executer
			
			return resolve(result);
		});
	});
}

// even better: utilizing a promisified method
var readFileP = util.promisify(fs.readFile);
var foo = async function() {
	var result = await readFileP("/tmp/someFile.txt"); // if this file doesn't exist, it throws, which is then wrapped in a promise rejection and able to be handled
	return result;
}

// Tip 7: async in async
async.series({
	first : function(cb) {
		db.table.find({}, cb);
	},
	// note when using an async function as a step in a series/parallel we no longer receive a cb argument
	second : async function() {
		return await dbPromise.find({});
	}
}, function(err, result) {
	
});

Editor preferences

Set your editor to the following settings to avoid common code inconsistencies and dirty diffs:

  • Use hard-tabs set to four spaces.
  • Trim trailing white space on save.
  • Set encoding to UTF-8.
  • Add new line at end of files.

Consider documenting and applying these preferences to your project's .editorconfig file. You can use the one in this Code Guide. Learn more about EditorConfig. Get it for Sublime Text or Atom