M Sheik's profileudooz!PhotosBlogLists Tools Help

Blog


    May 28

    Discipline in Object Orientation – [JavaScript – The Platform for Web 2.0 Part III]

    As per our "Anything on…" slogan, there are numerous ways we can define properties and methods for a class. This flexibility is more helpful in the implementation of bulky script animation, drag n drop, etc. But for a normal UI validation and business entity manipulation we have to follow a discipline. This will enable us to maintain and enhance a JavaScript code in long-time manner.

    Firstly, let us see the different ways to define a class.

    Object Declaration

    Way 1

    See the code snippet 1.

    function Point(x, y)

    {

    this.x = x;

    this.y = y;

    this.toString = function(){return "(" + this.x + "," + this.y + ")";}

    }

    var point = new Point(10, 5);

    alert(point.toString()); //shows (10,5)

    Code Snippet 1

    Figure 1 explains the nature of this approach.

    A class named "Point" is defined with two properties (x and y) and a method "toString()". All the definitions are bundled within "Point" constructor. But technically, there are two issues with this approach; both make this approach as not optimal:

    • Each instance of Point class will have its own copy of members (x, y and 'toString()'). It is feasible for "field" declarations, but harmful for "method" declaration. Each instances has their own copy of code for "toString()".
    • The arguments of above constructor (x and y) are global to all members. Yes, toString() can access the arguments "x" and "y". Is it optimal?

    Way 2

    As we know that "new" operator in JavaScript enables us to create instance of a class. The function followed by "new" means that it acts as a constructor for the class. The declaration and initialization are happened in the same place as like code snippet 1. Also, JavaScript does the more work. The lifecycle of an object creation is depicted in figure 2.

    1. Point class is declared and defined.
    2. An object of Point is created.
    3. JavaScript, creates "prototype" object with "constructor" property refers the Point constructor and add this as a property of point instance.
    4. If we defined Point as specified in code snippet 2, all the prototype specific members are initialized and added to point instance's prototype member.

    In figure 2, upto point 3, there is no different between way 1 and way 2. After instantiating Point with "new", JavaScript add an object "prototype" to the instance "point" as property. By default, "prototype" object has a property named "constructor". Whenever, prorotype is initiated, it assigns the corresponding object's constructor function to its "constructor" property.

    If we define the Point class properties and methods in its prototype object, then it can be sharable. That is, each instance has separate "property" values and share same function point. See code snippet 2.

    Point = function(x, y)

    {

    this.x = x;

    this.y = y;

    };                 

            

    Point.prototype.toString = function()

    {

    return "(" + this.x + "," + this.y + ")";

    }

    Code Snippet 2

    We can refactor code snippet 2 to create more discipline in the next article.

    May 21

    JavaScript – The Platform for Web 2.0 – Part II

    The next feature in JavaScript nowadays acts a protocol between web client and server. We know that there are two types of web development technologies available in the market.

    1. Pure server side technology. (ASP.NET, Servlet)
    2. Mixed mode technology. (PHP)

    The first one raises necessary level of abstraction between client and server side processing. Second one mixed with actual HTML page. Both have pros and cons. Most consumers wants the first one because of its abstraction and separation between UI rendering and UI processing. And it allows us to do object-design. Also, it provides more flexibility to interact with business services of a particular application.

    How do the client and this server side talks with each other? Till pre-Ajax, we did by passing a string of HTML/CSV/Plain text/XML. The more general and gentle approach is XML. But based on customer's SLA (Service Level Agreement), the developers selected the feasible one. In any approach, we need a to and fro converter on both server and client. In server, the result of a process (generally business entities or value objects) is converted to anyone of the above approach. In client, based on the approach we need to write JavaScript code to parse these values. We cannot fully say this approach is MVC's (Model-View-Controller) baby because the OO is missing here.

    Then now, is there any Ajax implementation to resolve this? Solution is available. But it is not an invention of Ajax. It is a feature of JavaScript. What is that?

    In JavaScript specification, it is called as object literals.

    Let us take one example. NJS Shopper is an online application for a grocery shop. After a customer placed list of items and paid online, the system finally shows him what are all items he ordered and price for these. The application server returns these information as a business entity named "OrderDetails". The figure 1 shows the details of this entity.

    Figure 1

    I am not going to explain the business details of the above. Before going further on how can we implement a protocol to speak both server and client in "object" context, let us see what Object Literals is?

    Object Literals

    We can create a JavaScript object (again object, not class) using object literals. All the members of an object can be declared as name-value pair with color separated. Each members are separated by commas and enclosed within {} as like arrays. For example,

    var orderDetails = {orderID:19092, customerName:"Sheik", netAmount:2184.00};

    Unlike C++/C#/Java, in JavaScript, we can create an object without any class declaration. One more proof of "Anything can be defined…" slogan.

    Now think that, instead of passing HTML, XML or plain text from server to client, we can create object literals at server side and send it to client. Then, JavaScript can process the object literals. At server side, we have to write a converter for the above entity to JavaScript object literals. For example, here I've written a very basic server side code snippet for OrderDetails excluding orders field in ASP.NET 2.0.

    StringBuilder orderDetailsBuilder = new StringBuilder();

     

    orderDetailsBuilder.Append("{");

    orderDetailsBuilder.AppendFormat("orderID:'{0}', customerName:'{1}', netAmount:{2}}}",

    orderDetails.OrderID, orderDetails.CustomerName, orderDetails.NetAmount);

    Response.Write(orderDetailsBuilder.ToString());

    Response.End();

    Caution: In .NET, using reflection we can generate object literals more general and in abstract manner. The above code snippet is just for example.

    The following code snippet shows that how to handle the returned object.

    var asyncReq = new ActiveXObject("Msxml2.XMLHTTP");

    asyncReq.onreadystatechange = function()

    {

        if (asyncReq.readyState == 4)

        {

            if (asyncReq.status == 200)

            {

              var resultString = asyncReq.responseText;

              var orderDetails = eval("(" + resultString +")");

              alert("Customer: " + orderDetails.customerName +

                  " Order ID: " + orderDetails.orderID +

                  " Net Amount: " + orderDetails.netAmount);

             }

        }

    };

    asyncReq.open("GET", "Default.aspx?a1=od", true);

    asyncReq.send(null);

    In AJAX period, this is called as JSON – JavaScript On Notation, a best protocol for server to client transmission.

    May 15

    JavaScript – Platform for Web 2.0

    I was excluded JavaScript in the "Web 2.0 basic things" intentionally, because JavaScript is the only choice for every web pages. But most of us know and/or use half the feature of JavaScript. JavaScript has more than these.  Lot of frameworks which target Web 2.0 and applications utilize these smart features. I would like to share some of these features which make JavaScript as a platform for Web 2.0 applications.

    If you know these, please have a look and share your knowledge.

    Before getting into these, keep the following statement in your mind about JavaScript:

    "Anything can be defined within the context of anything and assigned it to anything".

    Confused?

    Let's take an example, you can define a class from a function and enumerate its properties as array elements. And, you can treat an array as a object, function as data, etc. The following sections briefs about this.

    Lamda Functions

    Lamda functions are unnamed functions which can be assigned to a variable like assigning an expression. This is more or less similar to functional programming style. See the following example:

    var square = function(x){return x*x;}    

    alert(square(2)); // returns 2 * 2 = 4  

    Code Snippet 1  

    The square is actually a variable on which the function reference with the above signature has been assigned.

    What is the difference between normal named functions and lamda functions?

    Let us see the below code snippets:

    var square = function(x){return x*x;}    

    function twoSquare(square)

    {

        return square * 2;

     

    alert(twoSquare(square(3))); // returns 9 * 2 = 18

    Code Snippet 2

    In the above example, the lamda function "square" is passed as argument to "twoSquare" function as function reference. See the body of "twoSquare". It treats the function "square" as a variable.

    Also, you can assign or treat lamda function to object property and array element. The developers of "C" family can enjoy this feature.

    The lamda function simulates the C++ or C# style class declaration when creating a class. See the Code Snippet 3.

    function Customer(title, firstName)

    {

        this.title = title;

        this.firstName = firstName;

        this.getName = function(){return this.title + " " + this.firstName.toUpperCase();}

    }

     

    var amid = new Customer("Mr","Amid");

    alert(amid.getName()); // returns Mr AMID

     Code Snippet 3

     In code snippet 3, a class Customer has been defined. In this getName is a lamda function. Remember, getName is variable to the function reference.

    Let us see other features in succeeding articles.