Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Sunday, March 26, 2017

An Introduction to TypeScript

You may also like to see:

Initially, JavaScript language was introduced for the client side programming, later with the Node.js progress it started to become an emerging server-side programming language too. As you might know when you start developing an application with JavaScript and as its code starts to grow, at some points it gets complex and difficult to maintain.

Since JavaScript does not support the features like strong type checking, concepts of object-oriented programming and compile time error checks which make it a difficult language to code with. Also, these problems limit JavaScript usage for enterprise level applications development. TypeScript is developed to overcome these issues and make a reliable and better experience of coding with JavaScript. TypeScript is a promising change and will likely to make JavaScript much famous.

What is TypeScript?


Definition of TypeScript on its official site.

As stated in the definition of the official site, the TypeScript is strongly typed superset of JavaScript that generates the JavaScript, which means that TypeScript is JavaScript moreover it has some additional helpful features. TypeScript is a transpiler which generates the plain JavaScript, so at any point, if you are not comfortable with TypeScript syntax, you can start writing a JavaScript syntax code & it will work perfectly with TypeScript code.

TypeScript helps to code in structural programming style, using classes, interfaces, strong typing, modules and also it easily integrates with other popular JavaScript libraries. TypeScript is kind of wrapper on JavaScript that has extra features to help the developer.

TypeScript is developed by Microsoft and also it has been used to develop the Angular 2, which is also the reason that TypeScript gained so much attention recently. Having the support of two big tech communities means that there is a lot more to come in future and surely it is going to be a more stable tool.

Why TypeScript?


TypeScript is just a superset of JavaScript, it does not have any effect on the final output. So it is completely on you to use TypeScript or not. The reasons to use TypeScript is its great tools which help in larger projects where your code-base is larger, TypeScript helps to manage the code base.

Development Friendly Tools


As discussed earlier, with larger size projects JavaScript code gets messier and difficult to manage and if the code is not properly structured it gets nightmare to work on. Once project size gets bigger making refactoring or any kind of changes to existing code is very scary or kind of next to impossible task. TypeScript has some great tools to manage the larger code base, like navigation, IntelliSense, and easy refactoring. These are the tools that required for a large project.

With these great tools, any changes or refactoring in existing codes is less risky and time savings. The extensions like Resharper helps in utilizing these tools very effectively.

Object Oriented Programming flavor


With TypeScript you can achieve object oriented flavor in JavaScript, it allows you to create an interface, classes, implement inheritance. These are the concepts any developer having experience in OOP language can understand. Let's take an example that you are working on an application in which you have an object of User with different roles (i.e, Admin, EndUser etc), which has some basic user properties. Now if you are working on plain JS, you cannot restrict the definition of User object i.e, its properties and functions. That is the reason you might have different versions of the User object in different methods.

While using TypeScript you can define an interface for User objects and all roles will implement this interface so that we can make sure that object contains the required mandatory properties.
interface IUser {
   id: int; 
   firstName: string;
   LastName: string;
   email: string;
   //...
} 

class SuperAdmin implements IUser {
//other custom properties
} 
class EndUser implements IUser {
//other custom properties
} 

An important point here is that TypeScript gives these flavors of Object Oriented programming but not force it and as already discussed any valid js code is valid TypeScript code so a developer might start developing on concrete objects instead of these abstract implementation without any warning.

Readable and Easy to understandable Code


TypeScript adds details to the signature of function which makes it easy to understand. Let's take an example of jQuery ajax function, how descriptive it is?
jQuery.ajax(url, settings);
What information you can get from this line of code? It is a function which takes two arguments, what are those two arguments types? Is URL an object? what are settings object contains? its declaration has not clear information. To find the answers to above concerns you will require to see its source code or the jQuery documentation which is the overhead.
Let see the strong type declaration of the same function:

ajax(url: string, settings?: AjaxSettings): XHRObject;

interface AjaxSettings{
  cache?: boolean;
  async?: boolean;
  contentType?: any;
  headers?: {
     [key: string]: any;
  };
  //...
}

interface XHRObject {
  responseJSON?: any;
  //...
}
Let see what this function is telling us, it says ajax is a function which can take two arguments, URL which is a string and AjaxSettings is an optional argument, which is an interface and can only contain the properties of specific type, allowed by the interface definition also declaration tells us that this function will return XHRObject.

Migrating Existing Code


If you have existing written code you can easily migrate your js code to TypeScript code without much effort. Since TypeScript is just a superset of JavaScript and any valid JS code is a valid TypeScript code. So you can convert any existing .js file to .ts (TypeScript file extension). After switching file extension you can start changing dynamic types of your code to strongly typed. Once your are done with one module you can pick next module and your code is any time ready and functional whether its completely migrated to TypeScript or not.

You may also like to see:

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:

Friday, November 15, 2013

JavaScript : Prototype Property and Inheritance

You may also like to see:

In JavaScript each object has a property of Prototype, allow to add a property or function to an object.

In JavaScript there is no concept of class, you need to create an object, then you can extend it actually that object is in JavaScript is a class. Prototype allows to add new functionality to existing object like adding subString(),reverse() to a string object.

If we take this like we have a Employee class, there are different types of Employees like Managers, Supervisors, Agents etc. But each type is actually inheriting Employee.

Example (JsFiddle Demo):

//Define a functional object to hold employee in JavaScript
var Employee = function(name) {
    this.name = name;
};

//Add dynamically to the already defined object a new getter
Employee.prototype.getName = function() {
    return this.name;
};

//Create a new object of type Employee
var judy= new Employee("Judy");

//Try the getter
alert(judy.getName());

//If now I modify employee, also Judy gets the updates
Employee.prototype.alertMyName = function() {
    alert('Hello, my name is ' + this.getName());
};

//Call the new method on john
judy.alertMyName();

Here in above code we extended the base object, now we will create a child object and inherit it from base class (JsFiddle Demo).

//Create a new object of type Manager by defining its constructor. 
// It's not related to Employee for now.
var Manager = function(name) {
    this.name = name;
};

//Now I link the objects and to do so, we link the prototype of Manager 
//to a new instance of Employee. The prototype is the base that will be
//used to construct all new instances and also, will modify dynamically
//all already constructed objects because in JavaScript objects retain 
//a pointer to the prototype

Manager.prototype = new Employee();     

//Now I can call the methods of Employee on the Manager, let's try,
//first I need to create a Manager.
var myManager = new Manager('John Smith');
myManager.alertMyName();

//If I add new methods to Employee, they will be added to Manager,
//but if I add new methods to Manager they won't be added 
//to Employee. Example:
Employee.prototype.setSalary = function(salary) {
    this.Salary = salary;
};
Employee.prototype.getSalary = function() {
    return this.Salary;
};

//Let's try:       
myManager.setSalary(30000);
alert(myManager.getSalary());

judy.setSalary(60000);
alert(judy.getSalary());

//Now if I added a property to Manager 
Manager.prototype.Projects =function(){
    return "Handling multiple projects";
}

//Projects function will be available for managers instances
alert(myManager.Projects());

//it wont be available for employee judy
if((typeof judy.Projects) !== "function")
    alert('function not available');

While as said I cannot call Projects() on a Employee. Because parent class does not have implementation of child class function.

//The following statement generates an error.
judy.Projects();

How Prototype chain works?

When it calls the parent class function, it firstly find member in the current object of Manager, but as alertMyName() was not available there so it searches in prototype, and it keep finding until it find the function or find the prototype null.

Prototype chain can be extended as many level as required, each time by setting the prototype of the child class equal to an object of the parent class. If you do not use prototype then it becomes a static and only available for current object. As we know object in JavaScript is a class and making a static function only available for that particular object and for other object of same type cannot access the same function while creating function with prototype is available in all objects.

Here is a short example (JsFiddle Demo).

var myClass =function(){};
myClass.myFunction = function() { 
  alert('Hello Static Function');
} 
//current object will call it function as it associated to it
//it can be called with this object only
myClass.myFunction();
//now create instance variable
var objectOne = new myClass();
var objectTwo = new myClass();

//now calling myFunction with multiple instances will throw error
objectOne.myFunction();
objectTwo.myFunction(); 


on the other hand with Prototype (JsFiddle Demo):

var myClass =function(){};
myClass.prototype.myFunction = function() { 
  alert('Hello class Function');
} 

//now create instance variable
var objectOne = new myClass();
var objectTwo = new myClass();

//now calling myFunction with multiple instances will not throw error
objectOne.myFunction();
objectTwo.myFunction(); 


You may also like to see:


If you want to add something on this post please comments.
Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,