Jump to: navigation, search

Difference between revisions of "Horizon/Javascript"

(Required:)
(Required:)
Line 17: Line 17:
  
 
* ''Use “strict”, enclosing each JavaScript file inside a self-executing function.  The self-executing function keeps the strict scoped to the file, so its variables and methods are not exposed to other JavaScript files in the product.  Note: Using strict will throw exceptions for common coding errors, like accessing global vars, that normally are not flagged.
 
* ''Use “strict”, enclosing each JavaScript file inside a self-executing function.  The self-executing function keeps the strict scoped to the file, so its variables and methods are not exposed to other JavaScript files in the product.  Note: Using strict will throw exceptions for common coding errors, like accessing global vars, that normally are not flagged.
   Example: (function(){
+
   Example:  
 +
            (function(){
 
               'use strict';  
 
               'use strict';  
 
                 // code...
 
                 // code...

Revision as of 18:13, 17 September 2014

****** Under Construction ******

Code Style Guidelines

As a project, Horizon adheres to code quality standards. The following standards are divided into required and recommended sections. Our main goal in establishing these best practices is to have code that is reliable, readable, and maintainable.

JavaScript

Required:

Before committing your code, please review the following checklists: 'Reliable' and 'Readable and Maintainable'. Though we all have our preferences, these are the most commonly accepted guidelines.

Reliable

  • Use '===' as opposed to '==' for equality checks. The '==' will do a type cast before comparing, which can lead to unwanted results. Note: If typecasting is desired, explicit casting is preferred to keep the meaning of your code clear.
  • Keep document reflows to a minimum. DOM manipulation is expensive, and can become a performance issue. If you are accessing the DOM, make sure that you are doing it in the most optimized way. One example is to build up a document fragment and then append the fragment to the DOM in one pass instead of doing multiple smaller DOM updates.
  • Use “strict”, enclosing each JavaScript file inside a self-executing function. The self-executing function keeps the strict scoped to the file, so its variables and methods are not exposed to other JavaScript files in the product. Note: Using strict will throw exceptions for common coding errors, like accessing global vars, that normally are not flagged.
  Example: 
           (function(){
              'use strict'; 
               // code...
            })();
  • Use for each when looping whenever possible. AngularJS, and jQuery both provide for each loops that provide both iteration and scope.
  AngularJS:
    angular.forEach(objectToIterateOver, function(value, key) {
        // loop logic
    });

  jQuery:
    $.each(objectToIterateOver, function( key, value ) {
       // loop logic
    });
  
  • Do not put variables or functions in the global namespace. There are several reasons why globals are bad, one being that all JavaScript included in an application runs in the same scope. The issue with that is if another script has the same method or variable names they overwrite each other.
  • Always put var in front of your variables. Not putting var in front of a variable puts that variable into the global space, see above.
  • Do not use eval( ). The eval (expression) evaluates the expression passed to it. This can open up your code to security vulnerabilities and other issues.
  • Do not use 'with object {code}'. The with statement is used to access properties of an object. The issue with 'with' is that its execution is not consistent, so by reading the statement in the code it is not always clear how it is being used.


Readable & Maintainable

  • Give meaningful names to methods and variables
  • Avoid excessive nesting.
  • Avoid HTML and CSS in JS code. HTML and CSS belong in templates and stylesheets respectively. For example:
  1. In our HTML file, we should focus on layout.
     i. Reduce the small/random <script> and <style> elements in HTML.
     ii. Avoid in-lining styles into element in HTML. Use attributes and classes instead
  2. In our JS files, we should focus on logic rather than attempting to manipulate/style elements. 
     i. Something like element.css({property1,property2...}) belongs in a CSS class.
     ii. Something like $("<div><span>abc</span></div>") belongs in a HTML template file. Use show/hide/clone elements if dynamic
         content is required.
     iii. Avoid using classes for detection purposes only, instead, defer to attributes.  For example to find a div: 
         <div class="something"></div> 
          $(".something").html("Don't find me this way!");
          
         Is better found like: 
           <div data-something></div> 
            $("div[data-something]").html("You found me correctly!");
  • Avoid commented-out code.
  • Avoid dead code.


JSHint

JSHint is a great tool to be used during your code editing to improve JavaScript quality by checking your code against a configurable list of checks. Therefore, JavaScript developers should configure their editors to use JSHint to warn them of any such errors so they can be addressed. Since JSHint has a ton of configuration options to choose from, here are the options Horizon wants enforced. Here are instructions for setting up JSHint for Eclipse, Sublime Text, Notepad++ and WebStorm/PyCharm.

JSHint configuration file:

.jshintrc

Instructions for setting up JSHint:

JSHint setup instructions

Note: JSHint is part of the automated unit tests performed by Jenkins. The automated test uses the default configurations, which are less strict than the configurations we are recommending to run in your local development environment.

Recommended:

Readable & Maintainable

  • Put a comment at the top of every file explaining what the purpose of this file is when the naming is not obvious. This guideline also applies to methods and variables.
  • Source-code formatting – (or “beautification”) is recommend but should be used with caution. Keep in mind that if you reformat an entire file that was not previously formatted the same way, it will mess up the diff during the code review. It is best to use a formatter when you are working on a new file by yourself, or with others who are using the same formatter. You can also choose to format a selected portion of a file only. Instructions for setting up JSHint for Eclipse, Sublime Text, Notepad++ and WebStorm/PyCharm are provided.
  • Use 2 space for code Indentation.
  • Use { } for if, for, while statements, and don't combine them on one line.
// Do this          //Not this          // Not this
if(x) {             if(x)               if(x) y =x;
   y=x;                y=x;                          
}

AngularJS

Required:

  • Organization: Define your angular app under the root angular folder (such horizon/static/horizon/js/angular/hz.table.js). If your application is small enough you can choose to lump your Controllers, Directives, Filters, etc.. all in the one file. But if you find your file is growing too large and readability is becoming an issue, consider moving functionality into their own files under sub folders as described below.
  • Separate presentation and business logic. Controllers are for business logic, and directives for presentation.
  1. Controllers and Services should not contain DOM references. Directives should.
  2. Services are singletons and contain logic independent of view
  • Scope is not the model (model is your JavaScript Objects). The scope references the model.
  1. Read-only in templates,
  2. Write-only in controllers
  • Since Django already uses {{ }}, use {$ $} instead or {% verbatim %}
  • For localization of AngularJS templates in Horizon, there are a couple of ways to do it.
  1. Using gettext or ngettext function that is passed from server to client. However, this depends on the catalog object that is also passed from server to client. If you're only translating a few things, this methodology is ok to use.
  2. Use an angular directive that will fetch a django template instead of a static HTML file. The advantage here is that you can now use {% trans %} and anything else Django has to offer. You can also cache the page according to the locale if you know that the content is static.

Recommended:

  • Use these directories: filters, directives, controllers, and templates. Note: When you use the directory name, the file name does not have to include words like "directive" or "filter".
  • Put "Ctrl" on the end of a controller file name
  • Don't use variables like "app" that are at the highest level in the file, when Angular gives an alternative. For example use function chaining:
  angular.module('my_module').controller('my_controller', ['$scope', function($scope) {
     // controller code
  }]).service('my_service', ['$scope', function($scope) {
    // service code
  }]);