Wednesday, May 18, 2016

Java Script Development Guidlines


The aim of the page is to give practical and widely adopted industry best practises and guidelines for all phases of JavaScript development lifecycle. All the necessary tools and frameworks like code analysis and test frameworks are already integrated to our CI system and is ready for use and is already in use by teams

Part 1: Sensitizing with JavaScript language

  Persons coming from other languages may not appreciate certain coding guidelines that is recommended and set in  SONAR JS Analysis and that is also checked by popular tools like JSHint and JSLint;
Example the function below will return 'undefined' and not  'Hello World'. 
function main() {
 return 
 'Hello, World!';
}
main(); ->>return's 'undefined' 
This is because in JS semi columns are not mandatory and  JS will add semi colon automatically during code interpretation; So it will add a semicolon after return making the function return nothing; Such and other such quirks are present in the language which entails the need for mandatory code analysis integration.
If not already done already, kindly go through the web technology competence development page - Competence Building in Web Technology. This will give you a idea about JS , its flexibility ,power and the way to use it effectively.

Part 2: JavaScript Basic Development Guidelines 

Code Structuring 

The NEED - There is no public , private concept in JS; Everything is attached to the global  window name space; So if you add some global variables or functions and a JS library that you are including is doing the same then this will cause name space collisions; which basically means that you code may work in undefined ways. With portlets it becomes worse as the JS in one portlet can have the same function/object names  as the JS in another and it is pretty common porblem.
Solution:   Module Pattern where-ever possible ; or Nested NameSpace  where you need to create new objects

Option1 :Module Pattern --> See below; basically simulates private and public accessors via JavaScript Closures
var ContenPackModuleName = (function(){
   //module variable; this will be retruned; see below
var my ={};
     //private variables
var map=null;
var maploaded=false;
var markersArray = new Object();
   //private methods
var panToSelection = function(sitename){
var cachedsite = markersArray[sitename];
if(!cachedsite){
                     console.log("Site no in map yet");
return;
              }
              map.panTo(cachedsite.latlong);   
       };
//public method/s
       //Getting the browser width and height
var getbrowserWidthandheight=  function(){
var winW = 630, winH = 460;
if (document.body && document.body.offsetWidth) {
                     winW = document.body.offsetWidth;
                     winH = document.body.offsetHeight;
              }
if (document.compatMode == 'CSS1Compat' && document.documentElement &&
                       document.documentElement.offsetWidth) {
                     winW = document.documentElement.offsetWidth;
                     winH = document.documentElement.offsetHeight;
              }
if (window.innerWidth && window.innerHeight) {
                     winW = window.innerWidth;
                     winH = window.innerHeight;
              }
       };
      //Associate methods that you want to be visbile outside the module , public methods to the object that you return from this
my.getbrowserWidthandheight =getbrowserWidthandheight; //public methods
   return my;
})(ContenPackModuleName  );

Invoke from Another JS /JSP or HTML 
ContenPackModuleName .getbrowserWidthandheight();
>>Result eamplpel o/p --> Object   { winHeight 513 winWidth 1218 }

More details regarding this pattern 
 Option 2: Using NameSpace- Use this if you need to create new objects which is not possible with closures/module pattern

var KKR= KKR|| {} ; //check if the variable with name KKRexists.  If not, create a new variable with empty value
KKR.SiteCreation = KKR.SiteCreation || {};
KKR.SiteCreation.statusTable = KKR.SiteCreation.statusTable || {};
//Declaring a global function.  
KKR.SiteCreation.statusTable.setId = function(id) {
    KKR.Portal.Page.id = id;
}
This function can be accessed from any js like //KKR.SiteCreation.statusTable.setId(123);

Do not put logic in JSP

  (Scriptlets is the Java Code you typeaway between <% %> tags in JSP; This is a very common mistake done by almost everybody starting our from Java background; BEWARE )
   I t is a  bad practice and a  common beginner's error; neither  generate the HTML page in the Servlet (which is okay for HelloWorld but not for anything more complicated)
Second: Use JSP minimally and only if really needed  
So what is the way ? Here is the gist --> Instead of using a JSP, GSP, or ERB to assemble a page server side and send back HTML, we have the server send back just the dynamic data as JSON and have the page assembled in the browser :You can leave or read the rest of the LinkedIn  story  
When using JSP's  (minimally  and when  needed) use with already available taglibs (JSTL) or liferay provided (mandatory rule)

Use JSON for Servlet to JS communication

JSON is wonderful . In the Servlet side you can use either Google's GSON library to create JSON objects and JS can read JSON objects as is as it is a JavaScript Object; I
f it comes encoded in a string use a library

Use JavaScript Libraries for DOM Manipulation

Browser implementation of JavaScript methods vary;  It is highly recommended to use a high level JavaScript library like JQuery  for DOM manipulation.
Make sure that the library used supports all popular A grade browsers and not just some browsers or maybe latest browsers etc. Hence the recommendation for JQuery , Alloy UI 

Code Analysis -Mandatory prerequisite for  Code Review

The NEED - As illustrated in the beginning, there are certain conventions that need to be mandatorily followed in JS , unlike in other languages. Since the rules are too many to write here it is best thatcode analysis tools catch these. 
During development - JSHint Eclipse Plugin.
 This will help in development and also show at a glance in code review too.  Kindly install this
SnapShot from Eclipse IDE on  one file where it can dynamically check
 
JS  SONAR Pluging for monitoring in CI
 JavaScript: The Good Parts Doug Crockford videobookblog his tool-JSLint which is the basis of most other rules and tools today
(Doug Crockfords has invented JSHint , JSON etc and his advice is pretty good; but we should be pragmatic about this)
Unit testing (where ever JS logic needs to be tested)
Unit testing JavaScript - JSTestdriver
Java Script can do DOM manipulation as well as do client side logic . The logic part should be kept testable as much a possible and not intermingled with DOM manipulation everywhere. Wherever the logic is trivial then there is no need to unit test it. If there is some logic that needs to be tested the JSTestdriver can be used. Jasmine is another popular framework  which I have not used
Adding details regarding this in another post

External Links

Integration Testing - Selenium WebDriver

Selenium 2 /Selenium WebDriver based Test cases with TestNG (JUnit does not have test case tagging feature, else it can only be used)
 Selenium WebDriver can support all Grade A browsers including iOS and Android browsers,
  Note : It is very easy to create fragile test cases if you don’t use the technology right; I have added a post to describe these

Part 3: JavaScript Advanced Development Guidelines (optional)

Minify and optimize your JavaScript 

Use Google's Closure compiler to minify and optionally to optimize the  JS code; This needs to be mandatory if the JS code size is huge and a practise that is followed in the industry. Be careful of adnaced optimization levels as it needs JS code to be structured according to Google's JavaScript guidelines (and has bugs in generated code )
 Closure Compiler Compilation Levels (Recommended - SIMPLE_OPTIMIZATIONS  from experience with trying out only) 
Minifying  can be done as a java jar command or via the maven plugin for this and use it
Online Generation: http://closure-compiler.appspot.com/home   for trying out
Note- Minifying makes it difficult to debug; One way out of that which is supported by Firefox , chrome etc is using source-map compiler option for the closure compiler when generating the minified code.with this during debugging via browser tools the original source code can be seen.
Performance Driven Development 
WebPage Tuning- Browser Plugins
Tuning your pages the Easy Way –   PageSpeed Insights (by Google) - 
Other options
PET Runs GUI measurement- JMeter with WebDriver Plugin



No comments:

Total Pageviews