Saturday, February 2, 2013

JavaScript as Object-Oriented Language


As some of experienced Java, C++ or C# programmers I used to think JavaScript as some kind of elementary programming languages when compared to the full-fledged OO languages such as Java or C#, or C++. However even JavaScript cannot do some advanced and complex things which we can do using Java, C# or C++ it is still an programming language with OO features. And programmers normally are so used to class-type OO languages - Java, C++ or C# they would find it hard to understand and confusing how to use the OO features in JavaScript. The below is aimed to help skilled Java, C++ or C# programmer to grab the essence of JavaScript OO features in short time.


Object concepts in JavaScript


Contrary to the impression of me and some of Java developers, JavaScript thinks heavily with object. Almost everything in JavaScript is object. At the first glance it is not so obvious because JavaScript doesn't explicitly show this like Java, C++, C#. But it is true that most of things are dealt with objects in JavaScript. A number, a string, a date, an array, a function or a custom-made object are all objects even with some primitive type like numbers.

var myAmount = 123.456;
var myAmount = new Number(123.456);

In above example the first line will declare one variable myAmount with the given value. Actually JavaScript will create one Number object. It is the same as the second line does.
The meaning of object in JavaScript is the same as in Java, C++, or C#. An object is a collection of data stored as properties and the methods that can be used to manipulate the data in the object.
The below example demonstrate the properties and the methods of JavaScript object. In the first line we declare one string object with the value as "This is a string" and the second line the property length of this string object is used. And in third line we invoke a method called toUpperCase of the string object.


var myString = "This is a string";
alert(myString.length)
var upperCasedVar = myString.toUpperCase();
 

So far the object in JavaScript looks very similar as Java, C++ or C# although object creation in JavaScript sometimes is not so obvious.

 

What does object in JavaScript look like?


 

Objects in JavaScript have properties and methods. The properties are the name-value pairs and method. These are exactly same as Java, C# or C++.
But there are something different in JavaScript. Java, C++ or C# are all class-based Object-Oriented languages. All properties and methods must be predefined in the class from which the object is instantiated. In JavaScript you can don't need to predefine them. All you need to do is to add the property name to the object and then give the value to this property. That's it.


var myLaptop = new Object();
myLaptop.make = "DELL";
myLaptop.model = "Inspiron";
myLaptop.year = 2011;
 

In the above example we create one object as myLaptop and then we add three properties to this myLaptop object.
For the properties in JavaScript object there is one thing which cannot be done in Java or other OO languages: You can delete one property from the object using keyword delete.
//Creates a new object, myobj, with 4 properties.
var myLaptop = new Object();
myLaptop.make = "DELL";
myLaptop.model = "Inspiron";
myLaptop.year = 2011;
myLaptop.uer = "Mark Chen";

//Removes the a property, leaving myLaptop with only 3 properties.
delete myLaptop.user;

 

Methods in JavaScript is similar to the properties. Methods of JavaScript object are the normal JavaScript functions which are assigned to the properties of the object.
The below example shows that one function is defined and assigned to the object: myLaptop. It becomes the method of that object and you invoke this method in this object.
var myLaptop = new Object();
myLaptop.make = "DELL";
myLaptop.startup = function() {
      return "Startup is done....";
};
myLaptop.startup();
document.write(myLaptop.make + "  " + myLaptop.startup());

 

How do you create object in JavaScript?


 

JavaScript provides some built-in objects. String, Date, Array, Math and Object are mostly common used. You can also have the custom-built objects.
There are many ways in JavaScript to create an object. Actually we have seen two different ways to create objects in the above examples: using new operator and using object initializer.
The below are some examples of creating JavaScript objects using new operator and object initializer.
var myDate = new Date(2013, 2, 11);

var myObj = new Object();

var anotherObj = {};

var myLaptop = new Object();
myLaptop.make = "DELL";
myLaptop.model = "INSPRION";
myLaptop.price = 1150.00;

var anotherLaptop = {make: "DELL", model:"INSPRION", price:1150.00}

 

Besides the new operator and object initializer you can also use constructor function. This way is very similar to Java, C# or C++. Constructor function is a JavaScript function which is used to set the properties and methods for the object. You can use new operator to invoke this function. What you get is a JavaScript object.
function Laptop(make, model, price) {
    this.make = make;
    this.model = model;
    this.price = price;
    this.startup = function() {
        alert(make+" "+model+" is started up.");
    }
}

var myLaptop = new Laptop("DELL", "INSPRION", 1150.00);


Inheritance and Prototype


Inheritance is one of most important characteristics of OO language. In class-based OO languages such as Java, C++ or C# inheritance is implemented using class and subclass. JavaScript also provides inheritance. But it is implemented using another concept called prototype.

So what is prototype in JavaScript? A prototype is a property in an object and this property actually is a reference to another object. But this prototype property is a bit special: the object will inherit all properties and methods from its prototype object.
The below is an example of using prototype to add one property and one method to an object.


function Laptop(make, model, price) {
    this.make = make;
    this.model = model;
    this.price = price;

}

// Adding the property to the prototype of Laptop object
// Adding the method to the prototype of Laptop object
Laptop.prototype.user = "Mark";
Laptop.prototype.startup = function() {
      alert(this.make+" "+this.model+" "+this.user + " is started up.");
}
     
var myLaptop = new Laptop("DELL", "INSPRION", 1150.00);

// Invoke the startup method which is inherited from prototype
myLaptop.startup();

 

The prototype property in JavaScript object is just another object. When you invoke new operator against Laptop function. The object which is created will automatically has one prototype property set as one empty object. But you can override this empty object with the object you want. In the below example the prototype of Laptop is set to Computer object. So all Laptop objects will have the properties and methods of Computer object.


function Computer(user) {
      this.user = "Mark";
      this.startup = function() {
            alert(this.user + " is started up.");
      }
}

function Laptop(make, model, price) {
    this.make = make;
    this.model = model;
    this.price = price;
}

Laptop.prototype = new Computer("Mark");
     
var myLaptop = new Laptop("DELL", "INSPRION", 1150.00);

myLaptop.startup();

 


 


 

Monday, January 14, 2013

What is the use of static import?


The use of static import in Java is quite simple: to provide the convenience to Java programmers when they use some fields or methods from a static class.
For example in your codes you want to use abs(int ) from static class Math.   Normally your codes will be like:

double d1 = Math.abs(-0.29);
double d2 = Math.abs(-0.39);


With using static import you don't need to specify Math class you can directly use abs(int) method.


import static java.lang.Math.*;
double d1 = abs(-0.29);
double d2 = abs(-0.29);

You can see that: you could save some time when you have many places to use abs(int) method in your Java codes since you don't need to type in Math for each invocation.

But in my opinion if in you Java file you have multiple static classes you should be cautious with using static import.   It may reduce the readability of your Java codes.  Any new comer who reads your codes first time may want to know which staic class a particular method belongs to and he may find it a bit harder to do so becuase of static import. 

Wednesday, December 12, 2012

Specify Java compiler version in Maven

Sometime you want to compile your Java codes in one particular version in Maven it is quite easy to do so by specifying this in maven-compiler-plugin.  It is shown as:


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

In the above example you specify Java is compiled in verison 1.5 and generated classes are compatible with JVN 1.5.

Monday, December 3, 2012

XQuery Short Tutorial - Part 2


This is the second part of XQuery Short Tutorial.   To view the first part click on this url: XQuery Short Tutoril - Part1

Variables

In XQuery a variable is very easy to be identified.  All XQuery variables always start with $.

There are two types of variables: global variable and local variable.  

Global variable implies that it can be accessible from anywhere within XQuery.   Global variable is declared in the prolog part in XQuery.

Local variable is only accessible within the scope where it is declared such as in one FLOWR expression.

One thing needs to be remembered that once variables are assigned they cannot be assigned with new value.

Example 1

declare variable $displayedText as xs:string := ‘No result found based on the given conditions’;


In above example one global variable of xs:string type is declared and assigned a value:  'No result found based on the given conditions'.

Example 2

let $products := (<product>
                    <id>143</id>
                    <name>Cable</name>
                  </product>,
                  <product>
                    <id>234</id>
                    <name>Adapter</name>
                  </product>)
return $products


FLOWR expression

FLOWR expression is essential in XQuery body part.  Actually the body part of one useful XQuery is consisted of many FLOWR expressions. In order to use XQuery effectively you should master FLOWR expression.

FLOWR stands for For, Let, Order, Where, Return.  This expression is used to iterate, assign, filter, order and retrieve one XML document.

The below is a FLOWR expression.

Example 3

let $result := $flightOpsData/FlightLeg
for $flight in $result/InboundFlights
return $flight


This FLOWR expression first assign the node FlightLeg under variable $flightOpsData to a local variable $result and then iterates a list of nodes of InboundFlights under the variable $result and then retrieve the list back.

The next example goes further to add where to filter the nodes to be returned.

Example 4

let $result := $flightOpsData/FlightLeg
for $flight in $result/InboundFlights
where $flight/ArrivalPort=’SYD’
return $flight


The above FLOWR expression will retrieve the flights whose ArrivalPort is SYD.

In the above 3 examples we have seen Let, For, Where, Return already now we add the last one: Order to the expression.

Example 5

let $result := $flightOpsData/FlightLeg
for $flight in $result/InboundFlights
where $flight/ArrivalPort=’SYD’
order by $flight/ArrivalDateTime
return $flight


This FLOWR expression will retrieve all the flights whose ArrivalPort is SYD and the retrieved result will be ordered by flight’s ArrivalDateTime.

When we get here we have use all clauses in a FLOWR expression.   In the reality not all clauses are needed to present in the expression.   When we write FLOWR expression we need to keep in mind the following point:

·         Each FLOWR expression should have return clause as its last clause.  It is mandatory.

·         where and order are optional.

·         At least either one of let clauses or one of for clauses should be used.

·         You can have multiple let clauses or multiple for clause.

·         FLOWR expression can be nested.


Functions

Like functions in other languages XQuery functions provides specialised functionality. Functions will make XQuery programming easier since you can reuse these functionalities and don’t need to implement it yourself.  They also make XQuery much easier to understand and maintain.

There are many built-in functions available for you to use immediately in your XQuery.  Also you can develop your own custom functions.

The custom functions are defined in prolog part in XQuery

The below is one example of XQuery function.

Example 6

 (: Function used to convert the duration into minutes :)
declare function xf:total-minutes-from-duration( $duration as xdt:dayTimeDuration? )  as xs:decimal? {
       $duration div xdt:dayTimeDuration('PT1M')
 } ;


You can see from the above. One function has the function name, function parameters, return parameter and implementation part.

Implementation part of function actually is the same as the body party of XQuery.   You can static and dynamic portions to implement your functionality. 

The function in example 6 is called xf:total-minutes-from-duration.  Its input parameter is $duration of type xds:dayTimeDuration and it will return the value(s) of type xs:decimal.   The function implementation part is: $duration div xdt:dayTimeDuration('PT1M').

The input parameters and return parameter can be typed or untyped.

Typed parameter means that you specify the type of the parameter.   These types can be atomic value type or node type.

The below are some example of types.

Example 7

xs:integer
xs:boolean
xs:anyAtomicType
xs:string
node()
element()
tns:ProductType


Function parameters can have no type.   No type means that you can pass anything (atomic value, node type or empty sequence) to the parameter. 

Function parameters can have modifier following the parameter name.   These modifiers are: ?, *. +.

Modifier ? means that you can one item or empty.   * means one or more than one items or empty.   + means one or more than one items.

The above rules also apply to the return parameter of the function.


Let us see one example listed as below.  In this function there are 3 typed function parameters.  One is a specific element type, second atomic type and the last generic element type.  And the last one can be one element or a sequence of elements or empty.    The return type of this function is generic element type and can be a sequence of elements or empty.

Example 8

declare function xf:filterFlightOpsData(
      $flightOperationsQueryRS1 aselement(tns:FlightOperationsQueryRS),
      $requestDateTime as xs:dateTime,
      $sortedFlightOpsDataList as element(ops:FlightOpsData)*) as element()* {
    (:  Funtion implementation is omitted here for brevity   :)
};


Make elements and attributes dynamically

Just XSLT XQuery also has the capability to create the element or attribute dynamically.   And this is quite useful in using XQuery. 

Actually it is rather simple to do in XQuery.

This is used to create element dynamically.

element {element_name} {element_value}


This is used to create attribute dynamically.

attribute {attribute_name} {attribute_value}


The below is one actual example that uses dynamic creation of attribute.   FlightSegements has two attributes: one is ID which is statically created and NumberOfStops which is dynamically created depending on if $FlightSegment has this attribute or not.

Example 9

<FlightSegment ID="{data($FlightSegment/@ID)}">
   if ($FlightSegment/@NumberOfStops)
   then
       attribute {"NumberOfStops"}{data($FlightSegment/@NumberOfStops)}
   else
    () 
</FlightSegment>




Wednesday, November 28, 2012

XQuery Short Tutorial - Part 1


XQuery is a query and function language that is used to do the query over the XML document.  It is widely used in SOA and integration environment where XQuery is used to transform the messages from one form to another.  Here it has the same functionality as XSLT.  From this perspective XQuery and XSLT look the same.   But after looking inside there are still many aspects that they are quite different.  For example XSLT itself is a XML document while XQuery itself has its own syntax and structure.   For someone who is adept in XSLT will feel bit not accustomed to the way of XQuery at first.  Here I would like to present a short XQuery tutorial for the people who have some experience with XML, XPath and XSLT to use XQuery confidently as quick as possible.

There are two parts of this tutorials,   To view the second part click on this url: XQuery Short Tutorial - Part 2

What does a XQuery look like?

First let us look at what a XQuery look like and what structure it has.  A XQuery is mainly made up of two parts: a prolog and a body.   The prolog part comes first in the query.  The prolog contains various declarations delimited by the semicolons.   The body part is the portion that be executed by XQuery engine to generate the output.


Example 1 
xquery version "1.0";
declare namespace tns = "http://www.toic.com/response";
<tns:x>1234</tns:x>


The above example is one very simple valid XQuery.   The first line xquery version "1.0"; is XQuery declaration.   The second line is the prolog part of XQuery where the namespaces, global variables, functions and etc. are defined here.  Note that in each statement of declaration always ends with semi-colon ; .    The last line is the body part of XQuery.    This is the meat of XQuery.


Data model in XQuery
The data model of XQuery is based on two core components: Atomic value and node.

Atomic value is the simple data value without markup.  The examples of atomic values are xs:int, xs:dateTime, xs:Boolean and etc.
Node is referred as XML node which can be element, attribute, text or other XML constructs.

The below is one example of node in XQuery.
Example 2 
<tns:x>1234</tns:x>


The general term for atomic value and node is called item.   Multiple items can make up a sequence.
In XQuery the sequence is represented as a list of items delimited by comma.

The below are two examples of the sequence in XQuery.  The first one is a sequence of atomic values and the second one a sequence of nodes.

Example 3
1,2, 3.5, ‘Hello World’


Example 4
<x>
      <y>1234</y>
  </x>,
<x>
       <y>3456</y>
</x>


How XQuery generates the output
We have seen what one XQuery looks like and the data model it uses.   Now we will see how XQuery generates the output.  Let us execute the first simple XQuery (Example 1) and see the output of the first XQuery example.

The output of example is shown as the below:

<tns:x>1234</tns:x>

We can see from the above output comes from the body part of XQuery.  The body part of XQuery is the template of the output.  There are static portions and dynamic portions. When XQuery engine processes the body part it will output the static portions and generate the output for the dynamic portions or from function calls.  Static portion are the atomic type literals or node type literals.  Example 1 and example 5 show such static portions.  Example 5 is using atomic value literals and example 1 using node type literals.


Example 5

xquery version "1.0";
123, 345

The output of this XQuey is shown as:

123 345

The power of XQuery is mainly from the dynamic portions.   The dynamic portions are from the function calls (shown in example 6, 7, 8, 9, 10), global variables (in example 8 and 9), or a FLOWR (in example 10).  When XQuery find these dynamic portions it will do some computation first and then put the result into the output.

In the below example the body is a single function call,
Example 6


xquery version "1.0";
declare namespace math="http://www.toic.com/xquery/math";
declare function math:multiple($arg1 as xs:int, $arg2 as xs:int)
  as xs:int  {
   $arg1 * $arg2
};
math:multiple(2, 3)

The output will be:
6

 The below example will use two function calls in the body part.  Note that there is one comma between two calls.

Example 7
xquery version "1.0";
declare namespace math="http://www.toic.com/xquery/math";
declare function math:multiple($arg1 as xs:int, $arg2 as xs:int)
  as xs:int  {
            $arg1 * $arg2
};
math:multiple(2, 3),  math:multiple(3, 4)

 This will generate one sequence of integer values.
6 12

Example 8 shows that body part of XQuery is two global variables declared in the prolog part.  Here is also one comma between two variables.

Example 8
xquery version "1.0";
declare variable $displayedText1 as xs:string := 'Displayed Text 1';
declare variable $displayedText2 as xs:string := 'Displayed Text 2';
$displayedText1,$displayedText2

And the output is as the below:
Displayed Text 1 Displayed Text 2


Example 9 shows that body part of XQuery is one arithmetic expression using two global variables.
Example 9 
xquery version "1.0";
declare variable $d1  :=  2;
declare variable $d2  :=  3;
$d1*$d2


The output is the result of this arithmetic expression which is the product of two numbers.

6

Example 10 shows that body is using one FLOWR expression.