Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

Difference between revisions of "Orion/Coding conventions"

(Constructing URLs)
Line 195: Line 195:
  
 
=== Constructing URLs ===
 
=== Constructing URLs ===
Orion provides a shim for the [https://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#api URL API]. Load the shim in your module, and then call the <code>window.URL</code> constructor.
+
Orion provides a shim for the W3C [https://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#api URL API]. Load the shim in your module, and then call the <code>window.URL</code> constructor. You should always use the URL methods, rather than concatenate and encode strings by yourself.
  
 
&#x2714; Do this:
 
&#x2714; Do this:
Line 208: Line 208:
 
   var myurl = "http://foo.com/?param1=" + encodeURIComponent("first value") + "&" + encodeURIComponent("second value");
 
   var myurl = "http://foo.com/?param1=" + encodeURIComponent("first value") + "&" + encodeURIComponent("second value");
  
Note about URITemplate
+
Consider also using the <code>orion/URITemplate</code> module, which implements the [http://tools.ietf.org/html/rfc6570 URI Template spec].
  
 
== JS Documentation ==
 
== JS Documentation ==

Revision as of 17:12, 25 January 2013

This is a draft work in progress. If you have suggestions on good naming practices for JavaScript, CSS, and HTML, please raise a discussion on the Orion mailing list.

JavaScript

All member variables starting with an underscore ('_') or having the @private jsdoc tag, are internal and should not be referenced by clients. Such variables are subject to change or removal at any time.

Compatibility

In general, Orion's JavaScript code is targeted toward modern JS runtimes. This means you can (and should) use ECMAScript 5 features like Object.keys, Array.prototype.forEach, and so on. ECMAScript 6 features should not be used, as they are not yet widely supported.

Some of Orion's client bundles may have more strict requirements about what features are allowed. For example, the Orion Editor supports older browsers like Internet Explorer 8, and thus has to avoid most ES5 features (even Array.prototype.indexOf is not allowed in IE8).

References

Coding patterns

Here's a list of common JavaScript idioms, and the recommended way of writing them in Orion code. We highly recommend writing Orion code using the Orion IDE, as its built-in validator will catch a lot of possible coding errors and anti-patterns (like accidental globals, for example).

When in doubt about coding style, follow these general rules:

  • Favor ES5 features.
    • But don't use strict mode.
  • Favor W3C APIs.
    • If a well-supported spec exists, use it.
    • If a decent-looking spec exists but it isn't well-supported, write a shim for it, then use it.

Arrays

Testing if a value is an array

✔ Do this:

Array.isArray(value);

Looping through elements

✔ Do this:

array.forEach(function(item) {
    // ...
});

✘ Don't do this:

for (var i=0; i < array.length; i++) {
    // ...
}

Never do this:

for (var i in array) {
    // ...
}

Searching for an element with ===

✔ Do this:

var index = array.indexOf(item);
if (index !== -1) {
   console.log("Found it!");
}

✘ Don't do this:

for (var i=0; i < array.length; i++) {
    if (array[i] === item) {
       console.log("Found it!");
       break;
    }
}

Applying a transformation to an array

Use Array.prototype.map. ✔ Do this:

var array = [1, 2, 3, 4];
var doubled = array.map(function(n) {
    return 2 * n;
});

✘ Don't do this:

var array = [1, 2, 3, 4];
var doubled = [];
array.forEach(function(n) {
  doubled.push(2 * n);
});

Deciding if an element satisfies a condition

Use Array.prototype.some.

Determining if every element satisfies a condition

Use Array.prototype.every.

Removing elements that satisfy a condition

Use Array.prototype.filter.

Objects

Testing equality

Always use the strict equality === and strict inequality !== operators.

Testing for objectness

✔ Do this:

if (value !== null && typeof value === "object") {
    // use value as an object
    Object.keys(value);
}

✘ Don't do this:

if (typeof value === "object") {
    // use value as an object
    Object.keys(value);
}

The null check is required, because typeof null === "object".

Looping through an object's properties

✔ Do this:

Object.keys(object).forEach(function(property) {
    console.log('property: ' + property);
})

✘ Don't do this:

for (var property in object) {
    if (Object.prototype.hasOwnProperty.call(object, property)) {
        console.log('property: ' + property);
    }
}

Never do this:

for (var property in object) {
    console.log('property: ' + property);
}

Functions

Attaching a particular this context to a function

✔ Use Function.prototype.bind:

var context = { myfield: "Hello world" };
var func = function() {
    return this.myfield;
};
var boundFunction = func.bind(context);
boundFunction(); // Hello world


Creating a map

To create a map with string keys, we can use an "empty" object.

✔ Do this:

var map = Object.create(null);

✔ Or this:

var map = { };

Then use hasOwnProperty to determine if a given key is present in the map:

✔ Do this:

if (Object.prototype.hasOwnProperty.call(map, key)) {
    console.log("The key " + key + " was found!");
} 

Avoid using a truthiness check to determine key presence:

✘ Don't do this:

if (map[key]) {
    console.log("The key " + key + " was found!");
}

… Because you'll get false negatives if the key's value is a falsey value (like 0 or ""). But even correctly handling falsey values won't save the [] operator:

✘ Don't do this:

if (typeof map[key] !== "undefined") {
  console.log("The key " + key + " was found!");
}

… This will give a false positive in many JS runtimes if the the nonstandard property name __proto___ appears as a key. It's best to avoid the [] operator entirely and use hasOwnProperty.

Writing an event emitter

Use the orion/EventTarget mixin to inject event behavior into an object. After calling attach(), your object implements the EventTarget DOM3 interface, and can dispatch events to listeners.

define(["orion/EventTarget"], function(EventTarget) {
    var myobject = {};
    EventTarget.attach(myobject);

    myobject.addEventListener("coolevent", function(event) {
        console.log("Listener received an event");
    });
    myobject.dispatchEvent({ type: "coolevent" }); // every event must have a type
});

Asynchronous operations

Use orion/Deferred to manage asynchronous operations.

var deferred = new Deferred();

XMLHttpRequest and Ajax

In most cases you can use orion/xhr, which wraps the browser's native XMLHttpRequest into a promise.

xhr("GET", "/index.html").then(
    function(xhrResult) {
        console.log("Got response: " + xhrResult.response);
    },
    function(xhrResult) {
        console.log("An error occurred: " + xhrResult.error);
    });

Constructing URLs

Orion provides a shim for the W3C URL API. Load the shim in your module, and then call the window.URL constructor. You should always use the URL methods, rather than concatenate and encode strings by yourself.

✔ Do this:

define(["orion/URL-shim"], function() {
    var url = new URL("http://foo.com");
    url.query.set("param1", "first value");
    url.query.set("param2", "second value");
    var myurl = url.href; // http://foo.com/?param1=first%20value&param2=second%20value
});

✘ Don't do this:

 var myurl = "http://foo.com/?param1=" + encodeURIComponent("first value") + "&" + encodeURIComponent("second value");

Consider also using the orion/URITemplate module, which implements the URI Template spec.

JS Documentation

All JavaScript API use jsdoc syntax. The principle doc tags used are:

@param
Documentation of method parameters. See TagParam in the jsdoc wiki for further details.
@name
For specifying class names. The class name should match the RequireJS module name.
@lends
For specifying what class a prototype contributes to

References:

Library Objects

API library objects all fall under the 'orion' namespace. For example a library object for managing bookmarks might be called orion.Bookmarks.

Services

The DOM location of service objects is not defined. All services must be accessed via the service registry using the service's symbolic id. While concrete service implementations may be found in the DOM, such object names are not API and are subject to change at any time. Service symbolic ids follow the Reverse DNS naming convention (like Java packages).

JSON

Server requests and responses are represented by default as JSON objects. Object member names use title case ("Name", "ChildrenLocation", etc).

HTML

None of the HTML in Orion is API. The existence and contents of any HTML file is subject to change at any time. If you see something in Orion's HTML files that you need in your application, make your own copy.

CSS

Java

Java code on the server follows the standard Eclipse Naming Conventions. The project short name is 'orion', so all server bundles and packages start with org.eclipse.orion.

Provisional API packages use the x-internal or x-friends manifest attribute, and do not have internal as a segment in the package name. Use of PDE API tools is highly recommended to ensure you are using supported API.

Copyrights

The Orion server source code is licensed under the Eclipse Public License. The standard Eclipse copyright header should be used for these source files.

The Orion client code (HTML, CSS, JavaScript), is licensed under both the Eclipse Public License and the Eclipse Distribution License. Here is a sample copyright header to use in JavaScript source files:

/******************************************************************************* 
 * Copyright (c) <date> <contributor name> and others.
 * All rights reserved. This program and the accompanying materials are made 
 * available under the terms of the Eclipse Public License v1.0 
 * (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution 
 * License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). 
 * 
 * Contributors: <contributor name> - initial API and implementation 
 ******************************************************************************/

Back to the top