Tuesday, March 27, 2012

JavaScript Closure Under the Hood

Closure is perhaps the most talked about feature in JavaScript. This post will attempt to deal with just enough of the theoretical aspects for us to appreciate the inner workings of the language behaviour we take granted for. The context of this discussion is  not specific to any JavaScript engine implementation.

Omni-Closures


In his book Secrets of the JavaScript Ninja, John Resig gave an informal description of closure as "A closure is a way to access and manipulate external variables from within a function."
Here is a rudimentary manifestation of closure that echoes the above description:

var y = 6;             // y is a global variable

function getSum(x){
    var z = 0;         // z is a local variable of  
    return x + y + z;  // getSum, whereas y is 
}                      // an external variable to getSum

getSum(4);             //returns 10

The variable y is not a local variable of getSum and yet it's been operated on within getSum. Closures are at work even for the most trivial code we'd write and take granted for.

A more explicit show of closure is when the local variables of an outer function remains to be referenced by the inner function even after the outer function's execution is complete:

function setOperators(y){       // outer function
    var z = 5;               
    function getSum(x){         //inner function
        return x + y + z;
    }
    return getSum;
}

var getSumRef = setOperators(4);//outer function's execution is complete and returns the function getSum
                                //
getSumRef(1);                   //returns 10

Function Scope?


Simply put, the scope for an entity Z refers to what other entities Z has access to. In JavaScript, a variable is said to have function scope. Instead of a rigorous but lengthy definition for it, let's consider this structure instead:

var i = 1;

function x(a){
    var j = 1;

    function y(){
        var k = 1;
    }
}

In the perspective of function x, var j and function y are accessible because they are declared within x, that is, they are local to x. Function x cannot access var k since k is within function y, hence local to y, but not to x. So far, functions x and y's behaviour adheres to that determined by their respective scopes.

However, by the merits of closure, functions can access variables outside of its local scope. Specifically, function y can access var j, and function x can access var i.

A closure is formed for function y which preserves the environment which y was created in, allowing y continue to have access to that environment. The variable j and argument a (argument for function x) are two of the constituents in this environment.

A Naive Visualization of Scope and Environment


Albeit neglecting some important details, sometimes a casual visualization can provide a mental picture that would eventually lead to a fuller understanding. So here is the attempt:

For function x:
  • local scope is the yellow area
  • environment is the blue area
  • x can access variables in yellow(local) and blue(environment), but not in green

For function y:
  • local scope is the green area
  • environment is the yellow area, plus the blue area
  • y can access variables in green(local), yellow(environment), and blue(environment)

Now we're better equipped to appreciate Wikipedia's definition of closure:
"A closure is a function together with a referencing environment for the non-local variables of that function."

Inner Workings of Closure


For ECMAScript, the proper name for this referencing environment 'e' is called an Activation Object when e is the local scope of a function, and a Global Object when e is the global scope. The activation object keeps local variables, named arguments, the arguments collection and this as key-value pairs.
Every time a function is being executed, an internal object called Execution Context is created for that specific execution. Execution context keeps a list of all activation objects and global object for the respective function being executed.

For instance, for our previous sample snippet:
function setOperators(y){       
    var z = 5;               
    function getSum(x){         
        return x + y + z;
    }
    return getSum;
}

var getSumRef = setOperators(4);  

getSumRef(1); //returns 10                  

The corresponding execution context would be:

When a closure is not needed for a function to reference its non-local variables, the function's execution context is discarded along with its activation objects. However, since the inner function getSum references non-local variable z, and argument y, a closure is created.

The closure makes a reference to the activation object for the "var getSumRef = setOperators(4)" execution context. Hence, even when setOperators' execution is completed, getSumRef remains to have access to the variables and the function getSum for evaluating the addition for us.

Digging Deeper(and Broader) for the Whole Picture


Here we've really only seen an expansion on the term "environment" in the context of a typical closure definition. To get a complete view of how scopes are managed and what function execution entails, refer to the following excellent resources:
High Performance JavaScript
http://jibbering.com/faq/notes/closures/
http://perfectionkills.com/understanding-delete/




Sunday, March 18, 2012

jQuery Selector Inspired Controller in ZK 6's MVC Pattern

The MVC pattern is adopted pervasively among Web frameworks. Various flavours exist for the pattern but the common goal is to achieve separation of concerns.

Under the ZK framework, MVC implementation ultimately requires the Controller to gain reference to, and listen events coming from, the UI components in View. An interesting bit of ZK 6's MVC pattern is the CSS/jQuery Selector inspired mechanism in its Controller that makes this plumbing task simpler and more flexible.

ZK Primer


In simplicity, ZK is a component based and event driven Ajax Java framework. Understanding this basic description alone is enough to take us through its MVC pattern.

Component based

A component either declared in XML or in Java has its state maintained as a POJO in the JVM. A component is then rendered with a set of JavaScript instructions at client side.


Event Driven

Each UI component can listen to event(s). There's a variety of ways to register event listeners to the components.
Just to name a few here,
in XML:
<button onclick="...">
</button>
in Java:
Button btn = new Button();
btn.addEventListener("onClick", new EventListener(){...});       

MVC Nomenclature in ZK

The component declarations make up the View. Although it's possible to construct the UI in Java, akin to GWT or Swing, most would prefer writing mark-up in XML. A ZUL in ZK is an XML compliant page that contains the UI mark-up. One can consider a ZUL page as an Ajax enabled JSP page.

The Controller in ZK is a Java class that implements the Composer interface or extends any one of Composer's implementations. SelectorComposer is the target of our investigation in this post.

Selector Inspired Controller in Action


Consider a simple window that prompts a user to enter her name, email address, and select the journal she'd like to subscribe:

We'll examine how the server-side selector mechanism works in our controller class as we implement the following features:
  1. Displaying a list of the available journals for subscription in a combo box
  2. Clear all fields in this simple form when the "Clear" button is clicked

Let's first see the components in mark-up which our controller will work with:
<grid apply="lab.zkoss.mvc.SubscriptionComposer">
        ...
    <rows>
        <row>
            <label value="User Name"/>
            <textbox mold="rounded"/> 
        </row>
        <row>
            <label value="email"/>
            <textbox mold="rounded"/> 
        </row>
        <row>
            <cell ...>
                <label value="Please subscribe me to "></label>
                <combobox model="${journalListModel}">
                    <template name="model">
                       <comboitem label="${each.title}"/>
                    </template>
                </combobox>
            </cell>
        </row>
        <row>
            <cell ...>
                <button label="Clear" ..."/>
                <button label="Submit" ..."/>
            </cell>
        </row>
        </rows>
</grid>

In our controller class, to implement the said features under the ZK framework, we'd need to gain reference to the UI components so the list of available journals can be rendered in the combo box and the onClick event for the Clear button can be handled.

public class SubscriptionComposer extends SelectorComposer{

 @Wire("combobox")
 Combobox journalbox;

 @Wire("textbox, combobox")
 List<InputElement> inputs;
 
 
 public void doAfterCompose(Component comp) throws Exception{ 
  super.doAfterCompose(comp);
  JournalDAO jdao = new JournalDAO();
  List<Journal> journalList = jdao.findAll();
  ListModelList journalListModel = new ListModelList(journalList);
  journalbox.setModel(journalListModel);
  
 }
 
 @Listen("onClick = button[label='Clear']")
 public void clearAll(){
  for(InputElement i:inputs) i.setText("");
 }
}
Let's elaborate on how selectors are used.

The Controller's Scope

When a controller is "applied" to a component, all of the component's children components also become accessible to the controller. 

In our implementation, the grid component is applied with our controller:
<grid apply="lab.zkoss.mvc.SubscriptionComposer">
...
</grid>
Hence the grid and all of its children components define the scope which our controller SubscriptionComposer can take effect.

Component Wiring

The @Wire annotation on line 3 and 6 take in a CSS selector pattern as its parameter. With the pattern "combobox, the annotation associates the sole combo box in our UI mark-up with the Combobox instance, journalbox declared in the controller class.
One of the many alternatives to achieve the same exact wiring is to give the Combox an ID, for instance:

<combobox id="thisworks2">
...
</combobox>
and the parameter for the annotation would be:
@Wire("#thisworks2")
Combobox journalbox;

Component Initialization

Once we've obtained references to the UI components in View, we could initialize them accordingly.
The doAfterCompose method allows developers to insert instructions to be executed right after the component under effect and its children are created. It's a method invoked by the framework and must be implemented for all classes implementing the Composer interface; such as the SelectorComposer class which we're extending our SubscriptionComposer from.

For our hypothetical feature, we need to initialize our combo box by populating it with a list of journals available for subscription.
@Wire("combobox")
 Combobox journalbox;

 ...
 
 public void doAfterCompose(Component comp) throws Exception{ 
  super.doAfterCompose(comp);
  JournalDAO jdao = new JournalDAO();
  List<Journal> journalList = jdao.findAll();
  ListModelList<Journal> journalListModel = new ListModelList(journalList);
  journalbox.setModel(journalListModel);
  
 }

On line 11, the combo box which we obtained reference to via the selector mechanism, is given the model data we prepared on line 10. ListModelList is a wraper class that enables changes made in its wrapped collection to be updated on its host UI component accordingly.

<combobox model="${journalListModel}">
        <template name="model">
            <comboitem label="${each.title}"/>
        </template>
    </combobox>

Once the combo box is supplied with a list model, the template tag will iteratively create a combo item for each entry in the list model.

Event Listening

The @Listen annotation adds method clearAll, as an event listener for the onClick event, to the button matching the pattern button[label="Clear"].

@Wire("textbox, combobox")
 List<InputElement> inputs;
 
 @Listen("onClick = button[label='Clear']")
 public void clearAll(){
  for(InputElement i:inputs) i.setText("");
 }


As before, there're many alternatives to the selector pattern shown here. One possibility is cell:first-child button, since the "Clear" button is the only component that matches this pattern.

<cell ...>
        <button label="Clear" ..."/>
        <button label="Submit" ..."/>
    </cell>

The brevity of the clearAll method is made possible because a single annotation @Wire("textbox, combobox") in fact wired all fields in the UI to a list of ZK components.

In a Nutshell


In a typical ZK controller class implementation, before we can initialize a UI component, listen to its events, or change its state, we must first obtain a reference to that component.
This CSS/jQuery selector inspired controller gives us great flexibility in referencing the UI components of interest. A reference can be made by matching a component's ID, class name, component attributes, or by traversing through the component tree.
With this flexibility, changes made in the UI cause us minimum grief since the controller code can be updated as easily as coming up with new selector patterns.

References

ZK SmallTalks
ZK Developer's Reference

Monday, March 12, 2012

The Little Man Computer

The Little Man Computer presents a simplification of the modern computer architecture. This post will go through the LMC model and from there we'll infer what goes on inside the common computer when a program is executed. 

A Hypothetical Task for LM


We'll skip any formalities and deal with them later. Imagine if a little man, LM, is charged with the task of adding a given number x, no more than 3 digits, to an arbitrary number, say 22, then add their sum to another given number y. 
That is, performing x + 22 + y, where x and y are numbers we supply to LM. 


Set up LM an Office


Let's imagine the setting that must be provided to LM for him to do his job.

  1. he'll need a box to get the most recent number given from his user - an "In Basket"
  2. since LM reads one instruction at a time, he needs a set of boxes to help him store data and instructions alike - "100 Mailboxes" labelled from 00 to 99
  3. something to help him do the arithmetic - a "Calculator"
  4. an indicator, which can be reset, to let LM know which mailbox to look for the next instruction or data - an "Instruction Counter"
  5. a box that he could present the result to the user - an "Out Basket"


So we have an environment set up shown schematically like this:





What to Instruct LM



Now we turn our attention to instructing LM to carry out the addition of numbers. The following is the steps that we wish him to follow:

  1. LM fetches the number x, which we'd supply, and keys in x on the Calculator
  2. fetch the arbitrary number 22 which we stored in a mailbox and add it to x; this is feasible since the value of x is still on the Calculator
  3. LM stores the sum to a mailbox for later reference
  4. we'd supply LM with another number, y, which LM keys in on the Calculator
  5. LM retrieves the value of x+22 from the mailbox which he previously stored in step #4 and add it to y on the Calculator;  note the value of y was already entered in step #5
  6. LM puts the total sum of 3 number, x, y, and 22, to the Out Basket
  7. LM can now go on a coffee break

Note that step #4 is needed since in step #5 LM would punch in the value of y hence erasing the sum of x + 22. Each instruction is placed in its respective mailbox and LM will rely on the Instruction Counter to know which mailbox to go to next. Let's review the above instructions schematically:






How to Instruct LM



At this point, we know what instructions to give LM to do the job; here, we'll need to translate these steps into instructions that LM can understand.


For our simple task here we'll only need a subset of the complete LMC instructions available. Note that different implementations of the LMC exist so the instruction set varies as well. The table below summarizes the instructions needed to tell our LM to do his job:

Operation Mnemonic Machine Code
Input
IN
901
Output
OUT
902
Add
ADD
1xx
Store
STO
5xx
Data
DAT
xxx
Coffee Break
COB
000


Note: The x's for Add and Store refer to the mailbox numbers. x's for Data is the actual data value we wish to store in the next available mailbox


Machine code is understood by LM but tedious for people to memorize or write. So the operation codes (opcode) are expressed in mnemonics as shown in the table. We can now write the task instructions as follows:


IN              #copy the number x we supplied in In Basket onto the Calculator
ADD 07    #add the number, 22, which we stored in mailbox 7 to x
STO 08    #store the the result of x+22 to mailbox 8
IN              #copy the number y we supplied in In Basket onto the Calculator
ADD 08    #add the value we stored in mailbox 8 to the number y
OUT         #copy the value of y from the Calculator to the Out Basket
COB         #take a well deserved coffee break, ie. halt
DAT 22    #we place the arbitrary number 22 in the next available mailbox, 
                 #in this case, box 7 is available after all the instructions have taken up box 0 to 6



Give LMC a Test Run


Now that we have an imagination of how the LMC works, let's give the instructions a run on a LMC Simulator Applet, courtesy of University of Minnesota Duluth.



We'll now give LMC a run:
  1. type in the mnemonic instructions in the LMC Editor
  2. press the Assemble button to generate the machine code in the LMC Assembler window
  3. click the Load button in the LMC Computer window. Notice the machine code is displayed under the Memory field. Accumulator refers to LM's calculator. 
  4. click Step to follow the execution of our instructions. Notice the arbitrary number 22 is stored in box 7 and the sum of 22 and the first input, in this case 133, is stored in box 8, which is coherent with our instructions given.

Inference to the Common Computer Architecture


From the LMC model, we can take away some key points to help us to understand the common computer architecture (Von Neumann architecture).


Let's first map the LMC terms to their corresponding parts in a common computer:
1. The Little Man> The Control Unit
2. Calculator / Accumulator > Arithmetic Logic Unit
3. Instruction Counter > Program Counter
4. Mailboxes  > Main Memory
5. In Basket + Out Basket > I/O

The common computer components have the same roles to their LMC counter parts. The Control Unit and the Arithmetic Logic Unit (ALU) together make up the CPU. A simplified schematic diagram of a common computer is as such:




Under this architecture:
  1. both programs(instructions) and data are stored in memory
  2. ALU holds data temporarily until calculation is carried out
  3. program counter is incremented each time an instruction is fetched; the order of execution is sequential unless branching (we'll look into this in a post to follow) occurs
  4. Control Unit oversees the machine cycle: Fetch, Decode, and Execute. For instance, performing instruction 107 (mnemonic: ADD 07) stored in mailbox 01, upon reading the program counter for his next step to take, LM goes to mailbox 1 to retrieve the instruction 107, decoding 107 as 1 (the add operation) followed by the mailbox number 07, then execute the instruction (adding the data value stored in mailbox 7 to the value currently keyed in on the calculator).
We've just tapped into the concepts of LMC and how it models the common computer we so heavily rely on everyday. In later posts, let's look at how to get LMC to do more interesting things using branching etc. 








Prologue

This blog serves as a diary of my explorations, past or present, in technology.

Tech Dojo is made public so that ideas and techniques can be shared and validated among all who wish to participate.