Saturday, March 16, 2013

JavaScript Scope Chain

If you are not familiar with execution context, please go through this link first -- http://softtechhelp.blogspot.in/2013/03/execution-context-in-javascript.html
Scope is collection of current Activation context and all parent execution context's Activation objects.

Here is an example -
function one() {
    var a = 1;
    two();
    function two() {
var b = 1;
        three();
        function three() {
   var c = 1;
            alert('I am at function three with-a+b+c-' + a + b + c);
        }
    }
}
one();

In the above code the execution stack will have following stack of execution contexts -
Global -> One() -> two() -> three()
So if we talk about the scope of function three() then it becomes -
[AO of three()] + [AO of two()] + [AO of one()] +[AO of Global()]

If you see we are trying to print value a,b and c from function three(), but it has only c defined in it. So in order to find the value of a and b it will traverse in "[AO of two()] + [AO of one()] +[AO of Global()]" and check if these variables are available in there.

Lexical Scope - All functions are statically bound to its parent context. Which means in the above example function three() will always be bound to two(), which in turn be bounded to one() and so on.
Example -
var myAlerts = [];
for (var i = 0; i < 5; i++) {
    myAlerts.push(
        function inner() {
            alert(i);
        }
    );
}
myAlerts[0](); // 5
myAlerts[1](); // 5
myAlerts[2](); // 5
myAlerts[3](); // 5
myAlerts[4](); // 5

In the above example function inner() was created in global context, hence it is statically bound to global. Hence once we try to print the value of i, it checks if it has "i" defined, if not then it goes to its parent context, where it finds i to be "5".

Excercise -
// a globally-scoped variable
var a = 1;

// global scope
function one() {
    alert(a);
}
one(); // 1

// local scope
function two(a) {
    alert(a);
}
two(2); //2

// local scope again
function three() {
    var a = 3;
    alert(a);
}
three(); //3

// Intermediate: no such thing as block scope in javascript
function four() {
    if (true) {
var a = 4;
    }
    alert(a); // alerts '4', not the global value of '1'
}
four(); //4

// Intermediate: object properties
function Five() {
    this.a = 5;
}
alert(new Five().a); //5

// Advanced: closure
var six = function () {
    var foo = 6;
    return function () {
// javascript "closure" means I have access to foo in here,
// because it is defined in the function in which I was defined.
alert(foo);
    }
} ();
six(); //6

// Advanced: prototype-based scope resolution
function Seven() {
    this.a = 7;
}

// [object].prototype.property loses to [object].property in the scope chain
Seven.prototype.a = -1; // won't get reached, because 'a' is set in the constructor above.
Seven.prototype.b = 8; // Will get reached, even though 'b' is NOT set in the constructor.

alert(new Seven().a); //7
alert(new Seven().b); //8      

Execution Context in JavaScript

Execution Context can be visualize as Environment/scope the current code is being evaluated in.
As per ECMA  - When control is transferred to ECMAScript executable code, control is entering an execution context. Active execution contexts logically form a stack. The top execution context on this logical stack is the running execution context.

Browser is a single threaded environment. Only 1 thing can happen at a time, other actions will be queued in "Execution Stack".
Every function and constructor call enters a new execution context, even if a function is calling itself recursively. Every return exits an execution context. A thrown exception, if not caught, may also exit one or more execution contexts.

Lets take an example here -
(function foo(i) {
    if (i === 3) {
        return;
    }
    else {
        foo(++i);
    }
}(0));

In the above excample foo calls itself 3 times. Hence along with the global context, it creates 4 more execution context(for i = 0,1,2,3).

Execution Context has 2 stages -
1) Create stage - function called, but not yet executed-
1.1 Create Variables, functions and arguments
a) Create the arguments object, check the context for parameters, initialize the name and value and create a reference copy.
b) For each function found, create a property in the variable object that is the exact function name, which has a reference pointer to the function in memory.
c) For each variable declaration found, create a property in the variable object that is the variable name, and initialize the value as undefined.
1.2 Create Scope chain
1.3 Create value of "this"
2) Activation/Execution stage -
Assign values, reference to functions and execute


Execution context can be visualize in following object format -
executionContextObj = {
    variableObject: { /* function arguments / parameters, inner variable and function declarations , Can also be visualize as Activation Object*/ },
    scopeChain: { /* variableObject + all parent execution context's variableObject */ },
    this: {}
}

When the JavaScript engine invokes any function, it creates a new object (Activation object) and all the local variable defined within the function and the named argument passed to the function along with ‘arguments’ object get defined as properties of this activation object. The activation object is also added to the front of the execution scope chain.
In current scenario when control enters an execution context for function code, an object called the "Activation object"(stage 1.1) is created and associated with the execution context. The activation object is initialised with a property with name arguments and attributes.
The activation object is then used as the variable object for the purposes of variable instantiation.
The activation object is purely a specification mechanism. It is impossible for an ECMA Script program to access the activation object. It can access members of the activation object, but not the activation object itself.

Here is an example -
function foo(i) {
    var a = 'hello';
    var b = function privateB() {
    };
    function c() {
    }
}
foo(22);

After stage 1 -
fooExecutionContext = {
    variableObject: { // stage 1.1
        arguments: { // stage a
            0: 22,
            length: 1
        },
        i: 22, // stage a
        c: pointer to function c() // stage b
        a: undefined, // stage c
        b: undefined  // stage c
    },
    scopeChain: { ... }, //stage 1.2
    this: { ... } // stage 1.3
}

After Stage 2 -
fooExecutionContext = {
    variableObject: {
        arguments: {
            0: 22,
            length: 1
        },
        i: 22,
        c: pointer to function c()
        a: 'hello',
        b: pointer to function privateB()
    },
    scopeChain: { ... },
    this: { ... }
}

Reference -
1) http://davidshariff.com/blog/what-is-the-execution-context-in-javascript/
2) http://bclary.com/2004/11/07/#a-10

Saturday, March 9, 2013

Template Method and Adapter Pattern

Template Method -

- The template of the flow is provided by an abstract base class, and the implementation is done by derived or subclasses.
- Example if we write a parser, then we will provide the flow of parsing in the base class in the following way
parser {
parseFile(){
 load();
 parse();
close();
}
}

excelParser : Parser{
load () {//load excel}
parse(){//parseExcel}
close(){close excel}
}
pdfParser : Parser{
load () {//load pdf}
parse(){//parse pdf}
close(){close pdf}
}

Adapter-

- Provide an intermediate class which can help translating one interface into another compatible one.
- As a simplest example lets consider there is data from one stream in one format and our class expect it in another format. In this case we provide an intermediate class which can convert it into desired format, that intermediate class is adaptor class.

- We can understand it in the form of class adaptor as well, say there is class consultant and employee. Employee implements IEmployee interface but consultant doesn't. If we want to put consultant into a list of IEmployee then we will have to provide another class say ConsultantToEmployee which implements IEmployee and extends consultant.

By this we can have consultants also get saved in the list of IEmployee.

Design Principles

open-close principle -
- open for extension and closed for modification.
- example in strategy, we expose all the behaviors using interface. In future if we want to modify any behavior, or want to add any new behavior, we can do it, because we are calling interface(open for extension) not the concrete class object. The user class will not have to modify anything to achieve this(close for modification).

double dispatch-
- 2 calls to complete an operation.
- an object provides its own instance to some other class to get operated on it.
- Example - patient goes to doctor and then doctor operates on him.
This is what happens in visitor pattern. object of visitor is passed to the class, from there it calls visit method to get its functionality done.

Visitor pattern and Strategy Pattern


Visitor-

 - separate algorithm from object, which provides ability to add new feature without modifying the structure.
 - works on double dispatch principle.
 - Isolate the behavior from original class and provide it in other visitor class
 - pass the visitor object to the class, and then use this object to execute the behavior
 -Ex - there is a printer and we want to print from a machine.
precondition - every machine should have ExecutePrint method,hence we can have an interface for this.
printer will have overridden method for printing from different kind of machines.
pseudo code -
desktop m1 = new desktop ();
Printer p = new Printer();
m1.ExecutePrint(p);//accept
Printer{
Print(desktop d1){// print for desktop}
Print(laptop l1){// print for laptop}
}
Desktop{
  ExecutePrint(Printer p)
 {
    p.Print(this);//visit
 }
}
laptop{
   ExecutePrint(Printer p)
   {
      p.Print(this);
   }
}

Strategy -
Isolate the behavior using interface.
- every class will call behavior using interface only, at run time the object of concrete class(implementing interface) will be passed.
- At run time we can decide which kind of object we want to pass, as the whole implementation is done using interface, so any kind of object for which this interface is been implemented, can be passed.
- Example-
Say there is interface IBehavior , and all behaviors implement this.
Behavior1 : IBehavior {}
Behavior2 : IBehavior {}

Now the classes will use IBehavior in its implementation and when we are trying to create the object of the class, we can pass the object of either Behavior1 or Behavior2 and then the object will execute the code accordingly.

Friday, March 8, 2013

Factory Pattern and Singleton Patterns

Factory-
 - hide constructor(make it private)
 - expose a method which will provide you the required object.

advantages -
 - get rid of the repetition of "new" key word whenever we create objects.
 - abstract the implementation
whenever we provide some kind of library, its always good to provide a factory which will provide users the desired object, instead of exposing the class.

limitations -
 - private constructor will cause problem in inheritance

NOTE - making constructor protected will let us derive the class, but then we will have to provide the same getter method for subclass as well, else it will return the base object always, even if we call it on derived class.

Singleton-

 - only one instance of a class.
 - single instance, global access.

singleton vs static - singleton can be implemented using static as well. but static class can not implement any interface, unless interface is simply a marker.

limitations -
 - inheritance is not possible.
 - testing might become tricky.