Please click on any Advertisement, if you like this blog.

Thursday, September 5, 2013

Efficient coding style in ExtJs: Volume 2

.....being continued from "Efficient coding style in ExtJs: Volume 1"

Very important links related to this post:

9)  Avoid container over nesting: Always try to avoid unnecessary use of containers because each container creates one level of hierarchy and to access an item at the core, we have to traverse through the hierarchy of these containers. So, try to create your view with minimum possible number of containers.

10)  Functions should be small in size: Every function should be small, crisp and meaningful. Large functions reduces the readability, maintainability, reusability and debugging. Along with these, if an object (that consume huge memory) is instantiated at the start of function, it will live up to the end of function. So, if function is small, its local variables, objects etc will be garbage collected with in very short span of time and thus releasing the memory for other use.

11)  Try to avoid long object references: Always try to avoid using large object references as it will spend much time in traversing the object hierarchy to get the required component. E.g.

    var arrayLength = arrayObj.lenght;
    for( var I = 0; I < arrayLenght; i++){
                //anti pattern
                If(Abc.xyz.foo.bar.againFoo.againBar.finalObj === arrayObj[i]){
                                Alert(‘Anti pattern code’);
                }
   }

The above code can be rewritten in more efficient manner as follows:

    var arrayLength = arrayObj.lenght;
    var obj = Abc.xyz.foo.bar.againFoo.againBar.finalObj;
    for( var I = 0; I < arrayLenght; i++){
                //pattern
                If(obj === arrayObj[i]){
                                Alert(‘pattern code’);
                }
    }

12)  Hoisting problem should be avoided: javascript enables you to have multiple var statements anywhere in a function, and they all act as if the variables were declared at the top of the function. This behaviors  is known as hoisting. This can lead to a logical error when you use a variable and then declare it further in the function. For javascript, as long as the variable in a same scope (same function ), its considered declared even when it is used before the var declaration. E.g.

        // antipattern
        myname = "global"; // global variable
        function func() {
               alert(myname); // "undefined"
               var myname = "local";
               alert(myname); // "local"
        }
        func();

The first alert will say “undefined” because myname is considered declared as a local variable to the function. (Although the declaration comes after.) All the variable declarations get hoisted to the top of the function. Therefore to avoid this type of confusion, it’s best to declare upfront all variables you intend to use.

13)  Create efficient "for" loops: While iterating the Javascript collection in for loop, we should cache the length of collection in a variable and use that variable in for loop condition. E.g.

       for (var i = 0; i < myarray.length; i++) { //antipattern use of collection length
            // do something with myarray
       }

      //Right pattern
      var arrLength =  myarray.length;
      for (var i = 0; i < arrLength; i++) {
           // do something with myarray
      }

14)  Use hasOwnProperty(): It is important to use the method hasOwnProperty() when iterating over object properties to filter out properties that come down the prototype chain.E.g.

         var man = {hands: 2, legs: 2, head: 1};
         //somewhere else in the code
        // a method was added to all object
        If( typeof Object.prototype.clone === undefined){
                Object.prototype.clone = function(){};
        }

Somewhere before or after man was defined, the Object prototype was augmented with a
useful method called clone(). The prototype chain is live, which means all objects automatically get access to the new method. To avoid having the clone() method show up when enumerating man, you need to call hasOwnProperty() to filter out the prototype properties. E.g.

       // 1.
      // for-in loop
      for (var i in man) {
             if (man.hasOwnProperty(i)) { // filter
                    console.log(i, ":", man[i]);
             }
       }
       /*
          result in the console
          hands : 2, legs : 2, heads : 1
       */
       // 2.
      // antipattern:
     // for-in loop without checking hasOwnProperty()
      for (var i in man) {
           console.log(i, ":", man[i]);
      }
     /*
      result in the console
      hands : 2, legs : 2, heads : 1, clone: function()
    */

15)  Use “===” instead of “==”: JavaScript implicitly typecasts variables when you compare them. That’s why comparisons such as false == 0 or "" == 0 return true. To avoid confusion caused by the implied typecasting, always use the === and !== operators that check both the values and the type of the expressions you compare:

         var zero = 0;
         if (zero === false) {
               // not executing because zero is 0, not false
         }
         // antipattern
         if (zero == false) {
               // this block is executed...
         }

There’s another school of thought that subscribes to the opinion that it’s redundant to use === when == is sufficient. For example, when you use typeof you know it returns a string, so there’s no reason to use strict equality. However, JSLint requires strict equality; it does make the code look consistent and reduces the mental effort when reading code. (“Is this == intentional or an omission?”)

16)  Do not use Eval():Always remember the mantra that “eval() is Evil”.  This function takes an arbitrary string and execute it as javascript code.e.g.

         console.log(typeof un); // "undefined"
         var jsstring = "var un = 1; console.log(un);";
         eval(jsstring); // logs "1"
         console.log(typeof un); // "number"

So, here just by using eval we defined ‘un’ as a number literal. Suppose if the value of ‘jsstring’ is coming as an user input, how much security concern it may be. So, using eval() has security implications.

......To be continued in "Efficient coding style in ExtJs: Volume 3"

Very important links related to this post:


No comments:

Post a Comment

Please provide your precious comments and suggestion