Monday, May 13, 2019

Angular 7 - designed around the latest JavaScript features.

Development Env.
Install nodejs(javascript engine) and npm(catalog of development pkgs)
$node -v
$npm -v

Install Angular-CLI
$npm i -g @angular/cli

$ng version
Anglar CLI 7.0.1
.
.
.

Install Visual Studio Code(editor) → View → Terminal

Once you have Node.js, NPM, an editor, and a browser, you have enough of a foundation to start the development process.


$mkdir ng7Demo
$cd ng7Demoo
$ng new ng7App

1) would you like to add Angular routing? Y
2) which stylesheet format would you like to use ? Sass

$code .
This will open code file of application

package.json - list of the software packages that are required for a project.
tsconfig.json - TypeScript compiler requires a configuration file to control the kind of JavaScript files that it generates.
index.html - 


Starting Server
$ng serve
OR
$npm start

This command tells npm to run the start script, which starts the TypeScript compiler and the light-weight development HTTP server




________________________________________________________________________

Entry point into the world of Angular :-


1. Preparing the HTML File
index.html

<body>
 <todo-app>Angular placeholder</todo-app>
</body>

</html>

2. Creating a Data Model
model.ts

- ES5
var model = {
 user: "Adam",
 items: [{ action: "Buy Flowers", done: false },
 { action: "Get Shoes", done: false },
 { action: "Collect Tickets", done: true },
 { action: "Call Joe", done: false }]
};

When you save the changes to the file, the TypeScript compiler will detect the change and generate a file called model.js

- ES6

export class Model {
 user;
 items;
 constructor() {
 this.user = "Adam";
 this.items = [new TodoItem("Buy Flowers", false),
new TodoItem("Get Shoes", false),
new TodoItem("Collect Tickets", false),
new TodoItem("Call Joe", false)]
 }
}

export class TodoItem {
 action;
 done;
 constructor(action, done) {
 this.action = action;
 this.done = done;
 }
}

class keyword is used to define types that can be instantiated with the new keyword to create objects that have well-defined data and behavior.

export keyword is used to identity data or types that you want to use elsewhere in the application.

==> TypeScript compiler produced JavaScript code that will work in browsers that don’t implement that feature

"use strict";
var Model = (function () {
 function Model() {
 this.user = "Adam";
 this.items = [new TodoItem("Buy Flowers", false),
 new TodoItem("Get Shoes", false),
 new TodoItem("Collect Tickets", false),
 new TodoItem("Call Joe", false)];
}
 return Model;
}());
exports.Model = Model;

var TodoItem = (function () {
 function TodoItem(action, done) {
 this.action = action;
 this.done = done;
 }
 return TodoItem;
}());
exports.TodoItem = TodoItem;


3. Creating a Template
app.component.html 

a way to display the data values in the model to the user. In Angular, this is done using a template, which is a fragment of HTML that contains instructions that are performed by Angular.

<h3 class="bg-primary p-a-1">{{getName()}}'s To Do List</h3>

Including a data value in a template is done using double braces—{{ and }}—and Angular evaluates whatever you put between the double braces to get the value to display.

The {{ and }} characters are an example of a data binding, which means that they create a relationship between the template and a data value.

In this case, the data binding tells Angular to invoke a function called getName and use the result as the contents of the h3 element.

4. Creating a Component
app.component.ts

An Angular component is responsible for managing a template and providing it with the data and logic it needs. At the moment, I have a data model that contains a user property with the name to display, and I have a template that displays the name by invoking a getName property. What I need is a component to act as the bridge between them.


import { Component } from "@angular/core";
import { Model } from "./model";

@Component({
 selector: "todo-app",
 templateUrl: "app/app.component.html"
})

export class AppComponent {
 model = new Model();
 getName() {
 return this.model.user;
 }
}

import keyword is the counterpart to the export keyword.

decorator - which provides metadata about a class.

@Component decorator,it tells Angular that this is a component. The decorator provides configuration information through its properties, which in the case of @Component includes properties called selector and templateUrl.

selector property specifies a CSS selector that matches the HTML element to which the component will be applied.
templateUrl property is used to tell Angular how to find the component’s template.

class called AppComponent which provide the functionality required to support the data binding in the template. When a new instance of the AppComponent class is created, the model property will be set to a new instance of the Model class and getName function returns the value of the user property defined by the Model object.

5. Creating a Module / Putting the Application Together
app.module.ts

Every application has a root module, which provides Angular with the information that it needs to start the application.

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";

@NgModule({
 imports: [BrowserModule, FormsModule],
 declarations: [AppComponent],
 bootstrap: [AppComponent]
})
export class AppModule { }

6. Entry point into the application
main.ts

Angular applications also need a bootstrap file, which contains the code required to start the application and load the Angular module.

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule); // browser-based applications

code statements in the bootstrap file select the platform that will be used and load the root module, which is the entry point into the application.

7. Running the Application

The browser executed the code in the bootstrap file, which fired up Angular, which in turn processed the HTML document and discovered the todo-app element. 

The selector property used to define the component matches the todo-app element, which allowed Angular to remove the placeholder content and replace it with the component’s template, which was loaded automatically from the app.component.html file. The template was parsed; the {{ and }} data binding was discovered, and the expression it contains was evaluated, calling the getName and displaying the result.

Friday, May 3, 2019

Lambda expressions

1. Lambda expressions are just like functions and they accept parameters just like functions.
2. Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface. Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.

An example is java.lang.Runnable.


//Thread Example without lambda using anonymous class
        Runnable r1=new Runnable(){
            public void run(){
                System.out.println("Thread1 is running...");
            }
        };
        Thread t1=new Thread(r1);
        t1.start();
        //Thread Example with lambda  
        Runnable r2=()->{
                System.out.println("Thread2 is running...");
        };
        Thread t2=new Thread(r2);
        t2.start();

Java Lambda Expression Syntax
(argument-list) -> {body}

Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of expression.

3) Body: It contains expressions and statements for lambda expression.

_____________________________________________________________________

@FunctionalInterface  //It is optional
interface FuncInterface1
{
    // An abstract function
    void abstractFun();

    // A non-abstract (or default) function
    default void normalFun()
    {
       System.out.println("Hello");
    }
}

@FunctionalInterface
interface FuncInterface2
{
    // An abstract function
    void abstractFun(int x);

    // A non-abstract (or default) function
    default void normalFun()
    {
       System.out.println("Hello");
    }
}

interface Addable{
    int add(int a,int b);
}

class Test
{
    public static void main(String args[])
    {
        // lambda expression to implement above
        // functional interface.
        FuncInterface1 fobj1 = ()->{ System.out.println("lamda"); }; //No Parameter

        // This calls above lambda expression.
        fobj1.abstractFun();

 FuncInterface2 fobj2 = (int x)->{ System.out.println("lamda " + 2*x); }; //One Parameter
        fobj2.abstractFun(5);

        Addable ad1=(a,b)->(a+b);  // Multiple parameters
        System.out.println(ad1.add(10,20));
       
        Addable ad2=(int a,int b)->(a+b);  // Multiple parameters with data type
        System.out.println(ad2.add(100,200));

    }
}

Wednesday, May 1, 2019

Inheritance vs Composition

Inheritance is an "is-a" relationship. Composition is a "has-a".

Example: Car is a Automobile and Car has a Engine.

class Engine {} // The Engine class.

class Automobile {} // Automobile class which is parent to Car class.

class Car extends Automobile { // Car class extends Automobile class.
  private Engine engine; // Car class has an instance of Engine class as its member.
}

**************************************************************************

public class X{ 
   public void do(){ 
   } 

public class Y extends X{
   public void work(){ 
       do(); 
   }
}

1) As clear in above code , Class Y has very strong coupling with class X. If anything changes in superclass X , Y may break dramatically. Suppose In future class X implements a method work with below signature

public class X{ 
   public void do(){ 
   }
public int work(){
} 
}  

Change is done in class X but it will make class Y uncompilable. SO this kind of dependency can go up to any level and it can be very dangerous. Every time superclass might not have full visibility to code inside all its subclasses and subclass may be keep noticing what is happening in superclass all the time. So we need to avoid this strong and unnecessary coupling.

How does composition solves this issue?

Lets see by revising the same example

public class X{
    public void do(){
    }
}

public class Y{
    X x = new X();    
    public void work(){    
        x.do();
    }
}

Here we are creating reference of X class in Y class and invoking method of X class. Now all that strong coupling is gone. Superclass and subclass are highly independent of each other now. Classes can freely make changes which were dangerous in inheritance situation.

2) Second very good advantage of composition in that it provides method calling flexibility, for example :

class X implements R
{}
class Y implements R
{}

public class Test{    
    R r;    
}
In Test class using r reference I can invoke methods of X class as well as Y class. This flexibility was never there in inheritance.

3) Another great advantage : Unit testing

public class X {
    public void do(){
    }
}

public class Y {
    X x = new X();    
    public void work(){    
        x.do();    
    }    
}
In above example, if state of x instance is not known, it can easily be mocked up by using some test data and all methods can be easily tested. This was not possible at all in inheritance as you were heavily dependent on superclass to get the state of instance and execute any method.

4) Another good reason why we should avoid inheritance is that Java does not support multiple inheritance.

Lets take an example to understand this :

public class Transaction {
    Banking b;
    public static void main(String a[])    
    {    
        b = new Deposit();    
        if(b.deposit()){    
            b = new Credit();
            c.credit();    
        }
    }
}
Good to know :
composition is easily achieved at runtime while inheritance provides its features at compile time.

So make it a habit of always preferring composition over inheritance for various above reasons.

Summary:-
Composition - has-a relationship between objects.
Inheritance - is-a relationship between classes.

Composition - Composing object holds a reference to composing classes and hence relationship is loosely bound.
Inheritance - Derived object carries the base class definition in itself and hence its tightly bound.

Composition - Used in Dependency Injection
Inheritance - Used in Runtime Polymorphism

Composition - Single class objects can be composed within multiple classes.
Inheritance - Single class can only inherit 1 Class.

Composition - Its the relationship between objects.
Inheritance - Its the relationship between classes.

Web Development

Design Phase:- Below all these represent different stages of the UX/UI design flow:- Wireframes represent a very basic & visual repr...