Thursday, September 11, 2014

JavaScript and Date Object

Here is Previous Part of this series:

Today I came to know an interesting case of Date object in JavaScript, I decided to share with my readers. DateTime object is always problematic for developers, specially in Web project where you need to handle different time zones.

JavaScript has the core class of Date, which has many useful date function. As JavaScript is client-side language and it runs on clients browser so it creates the Date object of clients local time-zone, so you don't need to handle localization for client but when you get this value on server than you need to change it to UTC (or as per business requirements). You can easily create current date-time object using:
var dateTimeNow = new Date();
or you can pass the date fields to constructor:
var dateTime = new Date(year, month, day, hours, minutes, seconds, milliseconds); 
Date class has many useful and handy function which allow you to manipulate Date object and perform different operations. You can get day, month, year, hour from date object or you can convert it to UTC date object. Similarly you can change day, month, year or time of an object.
var dt = new Date();
dt.setFullYear(2014); 
dt.setMonth(9);       
dt.setDate(11);   
One important thing in JavaScript Date object every developer should know is its month start from zero so:
dt.setMonth(0);   //set January
dt.setMonth(1);   //set February
dt.setMonth(2);   //set march
dt.setMonth(3);   //set April
dt.setMonth(4);   //set May
dt.setMonth(5);   //set June

So What will happen if you set 12 to this date object?

If you are thinking it will give you an error then you are wrong because it won't. What actually JavaScript date object will do is it will consider January of next year on setting the 12. So it sometime may cause error or unexpected result which might confuse developer if they are unaware of behavior.
var dt = new Date();
dt.setFullYear(2014);
dt.setMonth(12);
dt.setDate(1);

alert(dt.toString()) //alert January 2015
Here is Demo

The inconsistent and confusing behavior I found for which I am writing this article is, setting Date to a date object.
If you set last date to a JavaScript date object in such a way that that date i.e, 31st for April, June, September, November or 30th ,31st for February. It will change the month.



For instance today is 20th of April 2014, and you coded to set 31st of October in way that you set the date first before changing month, Now if you are expecting Date object of 31st October than JavaScript is not your friend here as it will change the date object to October 1st 2014.

See code:
var dt = new Date(2014,3,20);  // 20th April 2014
dt.setDate(31);       //will change to 1st of May
dt.setMonth(9);       //1st October 2014

alert(dt.toString()) //alert 1st October 2014
Here is Demo

See it can be problematic and can cause a major defects if you ignored it. So always remember the following point in JavaScript Date object:
  1. If you are setting day of month than make sure to change month first than day.
  2. Remember month in JavaScript range from 0 to 11 (Jan - Dec)
  3. Be alert that JavaScript don't give error on setting month or date out from normal range.

Sunday, August 31, 2014

Object Oriented JavaScript : Inheritance, Polymorphism and Encapsulation

Here is Previous Parts of this series:

This is the third article of the series of Object Oriented JavaScript. In previous article we have seen private, public and static types of method.

Constructor


Lets start this article with Constructor as whenever you instantiate a class, you need to initialize some default values for this we initialize values in constructor but as in JavaScript Class is nothing but a function which contains methods and properties, so whenever you instantiate an object of JavaScript function /class it call that method so whatever you have initialize within the class will automatically be set. So you no need define separate constructor.
var Student = function () {
    console.log('Instance created');
    this.prop_one = "initialized value";
    this.prop_two = "initialized value";
};


var student = new Student();
console.log(student.prop_one); //initialized value
Here is Demo

Inheritance


Inheritance is one of the key feature of Object Oriented Programming, Inheritance can be achieved with prototype property. You can create a parent class and then inherit all the public methods and properties in child class. In JavaScript you do this by assigning an instance of the parent class to the child class. In ECMAScript 5 and above you can also use Object.create() to implement inheritance.

Lets see an example of inheritance in which we define a Human class and then inherit it in Student class and override some method of Human class.
// Define the Human constructor
function Human(fullName) {
  this.fullName = fullName;
}

// Add a couple of methods to Human.prototype
Human.prototype.speak = function(){
  alert("I speak English!");
};
Human.prototype.introduction = function(){
  alert("Hi, I am " + this.fullName);
};

See fiddle demo here.

Now we will create a child class of student

// Define the Student
function Student(fullName, school, courses) {

 //To initialize or call parent class constructor we need to Human.call()  
 //for call() we need to pass this instance
 //since fullName is Human class property inherited in student so we
 //passed it to parent class
  Human.call(this, fullName);

  // Initialize our Student properties
   this.school = school;
   this.courses = courses;
};

See fiddle demo here.

To inherit it from parent Human class we will set Student.prototype

//Do not try to set new Human() here as we are not calling it here
//calling Human here need to pass fullName property which is not available here
//the correct place to call parent object is in child class constructor
//as we call it in above Student function code
Student.prototype = Object.create(Human.prototype); // See note below

// Set the "constructor" property to refer to Student
Student.prototype.constructor = Student;
As object.create() only works in browsers support ECMAScript 5 and above so to achieve this in older browser you can create your own function:
function createObject(prototype) {
    function emmptyClass() { }
    emmptyClass.prototype = prototype;
    return new emmptyClass();
}

Student.prototype = createObject(Human.prototype);
Lets see its usage:
// Example:
var student = new Student("Ahmed","NED University", "Computer Science");
student.introduction();   // "Hi, I am Ahmed"
student.speak();       // "I speak English!"

// Check that instanceof works correctly
alert(student instanceof Human);  // true 
alert(student instanceof Student); // true

See here the demo.

Polymorphism / Overriding


Polymorphism is the main pillar of Object Oriented Programming, it refers to the ability of an object to provide different behaviors in different state of objects. For example Parent class Human define a function of introduction() in which it contains simple introduction but Student object override it by adding more detailed information for introduction. So now Human() object has its own implementation of introduction and Student() has its own. It will be invoked according to the state of object.

As we inherited the Human object in Student object we can override its public methods by changing its definition.
// override the "introduction" method
Student.prototype.introduction= function(){
  alert("Hi, I am " + this.fullName + ". I am a student of " + this.school + ", I study "+ this.courses +".");
};
or you can also add new methods
// Add a "exams" method
Student.prototype.takeExams = function(){
  alert("This is my exams time!");
};

Here is usage of above overriden method:
var student = new Student("Ahmed","NED University", "Computer Science");
student.introduction();   // "Hi, I am Ahmed. I am a student of NED University, I study Computer Science."
student.speak();       // "I speak English!"
student.takeExams(); // "This is my exams time!"

// Check that instanceof works correctly
alert(student instanceof Human);  // true 
alert(student instanceof Student); // true

See demo here

Encapsulation


Encapsulation is the one of the three pillars (Encapsulation, Inheritance and polymorphism) of OOP, It is a way of structuring data and methods by concealing the implementation or internal logic of object. Like in above example Human object contains the speak() method which is available in Student object but Student object does not know about the implementation of speak() method. It is encapsulated in Human object/class, child class inherit it as it is and change the methods which is different from its parent.

Summary


In this series of article we see how beautiful and impressive JavaScript is. It is as powerful as any other Object Oriented programming language is. In above series of article I used the words like namespace, class for objects which actually do not exist in JavaScript, just to map the JavaScript to the language you are aware of it. Please write your feedback about this series of articles in comments.

You may also like to see:

Sunday, August 24, 2014

Object Oriented JavaScript : Classes, Methods and Properties

Here is Previous Part of this series:

This is second part of Object Oriented Programming in JavaScript. I would recommend to see previous article on Object Oriented JavaScript before continuing this.

JavaScript is classless, there is no class keyword in JavaScript but you can achieve same via objects.

In first part we see, how interesting JavaScript is. It allow us to work on familiar Object Oriented way of programming like we use in other programming languages. In first part we learn about namespaces, core classes, custom classes and class instances in JavaScript and there is complete article on Inheritance in JavaScript through prototyping.

In last article we see that in JavaScript class in nothing but a function. So writing a class in JavaScript is as easy as writing a function.

Public Methods & Properties


Here is a Student class with some public properties and function.
var Student = function () {
this.first_name;
this.last_name;
this.courses = [];

this.fullName = function () {
return this.first_name + ' ' + this.last_name;
};
};

var student = new Student();

student.first_name = "Ali";
student.last_name = "Raza";
student.courses = ["JavaScript", "Object Orient Programming", "Functional Programming"];
var full_name = student.fullName()
console.log(full_name);
console.log('No. of Courses : ' + student.courses.length);
Here is JsFiddle Demo

Here in this example we used this keyword with function and properties to make it public. One thing which make JavaScript more powerful from any other OOP language is run-time changes in class structure. You can add new properties and function for any particular instance of function. So lets say in above example we add some more properties and function to an object:

var Student = function () {
this.first_name;
this.last_name;
this.courses = [];

this.fullName = function () {
return this.first_name + ' ' + this.last_name;
};
};

var student = new Student();

student.first_name = "Ali";
//runtime added property not present in class
student.middle_name = "H.";
student.last_name = "Raza";
student.courses = ["JavaScript", "Object Orient Programming", "Functional Programming"];
student.skills = function () {
return "Expert in JavaScript";
}

console.log(student.skills());

Here is JsFiddle Demo

One thing to notice in above example is that we have instantiate an object of Student class using statement var student = new Student() ; so the properties and function we adding to student object is only available to current object only. So if we created another object i.e, var student2 =new Student(); and try to call the skills() function with this it will throw an error.

 

Public Methods using Prototype


You can add public methods to a class using Prototype property then it will be available to all the instances of the class.
var Student = function () {
this.first_name;
this.last_name;
this.courses = [];
};

Student.prototype.fullName = function () {
return this.first_name + ' ' + this.last_name;
};
Here is JsFiddle Demo

 

Private Method & Properties

 

In class methods and properties we remove this keyword and introduce var keyword (recommended by strict mode of ECMAScript) then it will be a private function and properties.
var Student = function () {
    var private_property = "It is private property";

    var private_function = function () {
        console.log("This is private function");
    };
};

var student = new Student();
//will print undefine
console.log(student.private_property);
//this will throw an error private_function is not a function
console.log(student.private_function());

Here is JsFiddle Demo

Note here as we discussed above you can add new properties within object after creating an instance of class so here if you assign value to private_property it will create a new property in instance and assign value to it. JavaScript will not throw error on property creation.
var student = new Student();

//will print undefine
console.log(student.private_property);

//add new property same name of private property
student.private_property="set public content";

console.log(student.private_property);
Another point here to note is that you have created a public property of same name to the private property but class still maintain the private property with same value. So I was right in saying JavaScript is a race car you only need to know how to handle it.
var Student = function () {
    var private_property = "It is private property";

    var private_function = function () {
        console.log("This is private function");
    };

    this.checkPrivatePropertyValue = function () {
        console.log(private_property);
    }
};

var student = new Student();
//will print undefine
console.log(student.private_property);

//add new property same name of private property
student.private_property = "set public content";

console.log(student.private_property);
student.checkPrivatePropertyValue();
Here is JsFiddle Demo

Static Functions


To create a Static method for the class, you can add it with the class name.
var Student = function () {
    this.first_name;
    this.last_name;
    this.courses = [];
};

Student.StaticMethod = function () {
    return "Here is static content";
};
Here is JsFiddle Demo

Now you can call it anywhere directly with the class name.

So in this article we explore to declare the different type of methods and properties. If you have any feedback please do write comments.

Here is Next Part of this series:

Thursday, August 14, 2014

Object Oriented Programming & JavaScript

You may also like to see:

JavaScript is an excellent programming language. It is a race cars with so many gears, you just need to know how to handle it. JavaScript supports Object Oriented programming, it will not force it while compiling by throwing errors. But if you know how to write OOP code with JavaScript you can get all the aspects of OOP in JavaScript and believe me its amazing.


JavaScript supports object oriented programming because it supports properties, methods, inheritance through prototyping which are building blocks of OOP. Many developers avoid JavaScript because they are used to off writing OOP code with C#, Java or any other OOP programming languages and they don't know that JavaScript supports OOP and once you start writing code with JavaScript, It gives you encapsulated, re-usable and well managed object oriented code.

JavaScript Object Oriented Programming

Namespace


If you are C# or Java developer you must be familiar with Namespace. Namespace is a logical group of classes containing similar functionality under a unique name.In JavaScript Namespace is an object(namespace) which contains other objects, functions (classes). There is no difference in Namespace object and class object used in JavaScript unlike C# or other OOP languages.

Here is an example of namespace
// global namespace
var OOPJS = OOPJS || {};
Here in above code it is checking if namespace(object) of OOPJS is already existed within applications then use the same object but if it is not created then it create an empty object and initialize our object(namespace). Now this namespace is ready to contain the classes(function) and properties.

You can write your namespace helping function or common variables, functions across the namespace within this namespace.
// Create container called OOPJS.Helpers for common methods

var OOPJS = {};
OOPJS.Helpers = {

    //common variables
    global_variable: "Object Oriented Programming",

    //common methods
    myNamespace: function () {
        return "OOPJS";
    }
}
console.log(OOPJS.Helpers.global_variable);
console.log(OOPJS.Helpers.myNamespace());


See here demo.

Core Classes/Objects

JavaScript has many object (classes) available for use, like in C# there is Math object which contains static function abs(), round() etc, same concepts available in JavaScript. There are objects like Math, Object, Array, Number, Date, JSON, String and others.

See here a math object random() function which generate a random value.
console.log(Math.random());


Like Math there is object Object available which contains  prototype, create() [ECMAScript 5 and above] and many others. Since specified built-in objects have the object referred to by Object.prototype in their prototype chain by default therefore all the properties and functions of Object is inherited to that object. Note all these methods and properties also inherited to namespace too since it is also an object.

So if you want to add a function to all the objects, you can add it to Object using prototype property.

Custom Classes/Objects

The Class
JavaScript contains no separate class declaration like C#, Java or other programming languages. In JavaScript class is a function which contains methods and properties.

Here is a class declaration:
function Person() { } 
//or 
var Student = function(){ }
Class Instance
To create an instance of class we use new keyword with the class name, which instantiate a new fresh instance of class.


Here we declare a class and then created two instance of the class.
function Student() { }
var student1 = new Student();
var student2 = new Student();

In next article we will see classes in details with different access modifiers and other aspects of Object Oriented Programming in JavaScript. Please comment your valuable feedback and suggestion for improvement of this post.

Here is Next Part of this series:

Sunday, July 20, 2014

Git - Branches and Conflict Merge

While working on a project, you do not want your uncompleted task code to cause a state where the project is not in the executable state. To overcome these situations you need project branches. Whenever you start a new task you create a new branch and write all your code to that branch and once you are done with task implementation and testing you merged that branch to the main branch and all developers now can access it.

To create branches and merging branches in Git lets see a workflow which we see while coding in our project. You’ll follow these steps:
  • You are working on a website.
  • Create a branch for a new issue/story.
  • Started implemented that issue fixes or story.

At this point, testing team found a critical issue on production and you must need to fix that issue at priority. Now you will:
  • Switch to Master/Production branch.
  • Create a branch to add the Patch.
  • After it’s tested, merge the Patch branch, and push to master branch.
  • Switch back to your original story and continue coding.

Git Branching


Initially, you are on the master branch where you already have some code commits.

You have started working on a new Story. You want to isolate your code from the master branch until the story is completely implemented and tested. So you will create a new branch for this story. To create a branch and switch to it at the same time, you can run the git checkout command with the -b switch:

$ git checkout -b story12
Switched to a new branch 'story12'
This is shorthand for:
$ git branch story12
$ git checkout story12
Now you work on the story and make changes to some files.
$ git add folder/file.html folder/file2.html
$ git commit -m 'added some new pages for story 12'

Now at this point testing team found a vulnerability in the website which needs to be fixed on urgent basis.You don't want to revert all your code you have written for Story 12 so now all you have to do is switch to master branch. But before switching to the master branch you need to commit or stash all your work otherwise, Git would not let you switch the branches until your current branch is not in a clean working state.
$ git checkout master
Switched to branch 'master'
Now you are at a point from where you started coding for story 12, so there is no extra code which is different from the code which is in production. So now you can create a new branch for Patch on which to code for the fix of vulnerability until it's completed and tested.
$ git checkout -b patch
Switched to a new branch 'patch'
$ vim design.html
$ git commit -a -m 'fixed the vulnerability'
Now when you are sure that fix has been completely implemented for the issues, you can merge your patch branch to master branch. You do this with the git merge command:
$ git checkout master
$ git merge patch
Now after complete testing you can deploy master branch to production.

Now when you are done with Patch fix and it's successfully deployed, you can switch back to your story which was incomplete. Here as you are done with Patch branch and you are sure that you won't need it now. You may delete it from Git. To delete it use the -d option to git branch:
$ git branch -d patch
Deleted branch patch (was 9d0574w).
Now switch back to your story.
$ git checkout Story12
Switched to branch 'Story12'

Here in Story12 branch, it has not the code you did for Patch branch. Now there are two options either you pull the master branch and merge master branch to your story12 branch immediately or you can wait until completion of Story12. It depends on the project requirement.

Basic Merging



When your story implementation is completed and tested and ready to be merged into the master branch. To merge the branch you have to check out the branch you wish to merge into and then run the git merge command:
$ git checkout master
$ git merge Story12
Auto-merging README
Merge made by the 'recursive' strategy.
README | 1 +
1 file changed, 1 insertion(+)
Now that your work is merged in, you have no further need for the Story12 branch. You can delete it:
$ git branch -d Story12

Merge Conflicts


Sometimes while merging there come a situation when two different branches have changed the same part of a file. In that case, Git shows the conflict in files where Git would not be able to merge them cleanly. If your Story12 branch and Patch branch have changed the same part of files then Git will prompt you a conflict:
$ git merge Story12
Auto-merging file.html
CONFLICT (content): Merge conflict in file.html
Automatic merge failed; fix conflicts and then commit the result.
Git won't automatically commit a new merge in conflict case. Here you need to resolve the conflicts of the files. If you want to see the files which are unmerged due to conflict, you can see it by:
$ git status
On branch master
You have unmerged paths.
(fix conflicts and run "git commit")

Unmerged paths:
(use "git add ..." to mark resolution)

both modified: file.html

no changes added to commit (use "git add" and/or "git commit -a")

Git add the conflicts marker to files which has conflict like this:

<<<<<<< HEAD
Here is content
 =======
Here is updated contact
>>>>>>> Story12
The code between <<<<<HEAD to ======= is the code which was in master branch while code from ======== to >>>>>Story12 is code from Story12 branch. Here you have to decide which code you want to keep safe and which to remove and once you completed resolving conflict.

You can run git status again to verify that all conflicts have been resolved:
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD ..." to unstage)

modified: file.html
If you’re done with conflict resolution, you can add an commit the files:
$ git add file.html
$ git commit 
Now merge the branch:
Merge branch 'Story12'

Conflicts:
file.html
#
# It looks like you may be committing a merge.
# If this is not correct, please remove the file
#       .git/MERGE_HEAD
# and try again.
#
Git shows the default merge message you can edit and update with required details and information of merge.

Now you are done all of Story12 branch code, Patch branch and master branch is merged in the master branch.
Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,