Thursday, September 30, 2021

why to use call method in Javascript?

 let's look at an example ,

var john = {

    name: 'john',

    job: 'engineer',

    age: 35,

    presentation: function (style, timeOffDay) {

        if (style === 'formal') {

            console.log('Good ' + timeOffDay + ',ladies and gentlemen i\'m ' + this.name + ' working as ' + this.job + ' and i\'m ' + this.age + ' years old');

        } else if (style === 'friendly') {

            console.log('Good ' + timeOffDay + ',ladies and gentlemen i\'m ' + this.name + ' working as ' + this.job + ' and i\'m ' + this.age + ' years old');


        }

    }

};

john.presentation('formal','morning');

var smith={

    name:'smith',

    job:'teacher',

    age:40

};

john.presentation.call(smith,'friendly','evening');

Here,john is an object which have a method presentation . Now we have created another object smith without any method .But i don't want to create new method for smith object but want to use method of john object .
So,what can we to do achive this?
We can borrow method of john by calling call method and setting this variable to smith as the first argument.

john.presentation.call(smith,'friendly','evening');



Wednesday, September 29, 2021

Closure in Javascript

 An inner function has always access to the outer function's  variable and parameters even after the outer function has returned . Lets understood with a simple example,

function retirement(retirementAge){

    var a="years left until retirement";

    return function(yearOfBirth){//inner function

        var age = 2016-yearOfBirth;

        console.log((retirementAge-age)+a);

    }

}

var retirementUS=retirement(66);

retirementUS(1990);

we already know about lexical scoping , an inner function has access to the variable of the outer function . When a function gets called it is invoked into execution context .Then VO(variable  objects) stores the variable, and the scope chain keep track of the variables to use by the function . When a function returned it will popped up from execution context . So the execution context gets cleared .When the inner function invoked then it is gets called into execution context ,then how inner function can access to the outer functions variable . It is possible only for closures. 

The scope chain always stays intact .We no need to define closure manually . It is built into javascript. Javascript is always do this for us automatically .

Tuesday, September 28, 2021

Why to use mockito?

 Suppose we have a class which have a dependency which will provide some data and based on those data we will do some work,

public class SomeBusinessImpl {

private DataService dataService;//dependency

public SomeBusinessImpl(DataService dataService) {

super();

this.dataService = dataService;

}

int[] data = dataService.retrieveAllData();

int greatest = Integer.MIN_VALUE;

int findTheGreatestFromAllData() {

for (int value : data) {

if (value > greatest) {

greatest = value;

}

}

return greatest;

}

}

interface DataService {

int[] retrieveAllData();

}

Test class:

class SomeBusinessTest {

@Test

public void findGreatestFromAllData() {

SomeBusinessImpl someBusiness = new SomeBusinessImpl(new DataServiceStub());

int result = someBusiness.findTheGreatestFromAllData();

assertEquals(24, result);

}

}

class DataServiceStub implements DataService {//Implementation of DataService

@Override

public int[] retrieveAllData() {

return new int[] { 24, 10, 12 };

}

}

What to do if the logic inside DataServiceStub changed. Every time we will need to give different implementation of the DataService . But if we can create mock using mockito . By using mockito we can easily create dummy data .


Tuesday, September 21, 2021

@BeforeClass,@AfterClass,@Before and @After annotation in Junit ?

 @BeforeClass:  This is annotation is used in that method when there need such situation to do some prior works when test class is loaded in memory. Ex: DB connection establishment.

@Before: This annotation is used when need to do some works before @Test is execute.

@After:    This annotation is used when need to do some works after @Test is execute.

@AfterClass: Is called and execute after all the operation has done in the Test class.

@BeforeClass and @AfterClass runs for once in every test class

Monday, September 20, 2021

What is Junit and how it works?

 Junit is a unit testing framework for java programing language. It is necessary for test driven development.

 To include Junit in project create another source folder and create a class for Junit testing .

Then Junit jars will include in classpath.

When runs a Junit test it first create the instance of the Junit class then call the method annotated with @Test.

Keep in mind-Absence of fail() it is success in Junit.

Saturday, September 18, 2021

IIFE(Immediately invocation function expression)

 Suppose we want to declare a variable that can not be accessed outside of a block ,that means we want a private variable then we can define a method and create a variable inside the method and then can call the method from outside .So, because of scope chain the variable cannot be accessed outside of the block .But there is a problem is that only to declare a private variable we are creating a whole function and it becomes unnecessary .So there is a new concept IIFE introduced.

Ex:

function game(){

var score = Math.random()*10; //Here score variable can't access from outside of the function.

console.log(score>=5);

}

game();


We can write above function using IIFE,

(function(){

var score = Math.random()*10; 

console.log(score>=5);

})();//calling the function .

normally if the function is annonymous and have body then javascript parser treat it as a function declaration .

But if we wrap this function into parentheses-() then javascript parser treat it as function expression .then we called it . Here score variable is no longer accessed outside of the scope.


How to load data from properties file?

 We need to store data using a key in property file .Then use @Value annotation over a variable which will hold that data .Then we should use another @PropertySource annotation is used to provide properties file into spring environment .

Ex:

Suppose we have a url in app.properties file as

external.service.url = http://helloworld.com/hello


Now we have a service class which will provide this url .

@Component

public class ExternalService{

       @Value("${external.service.url}") 

       private String url;

        public String getUrl(){

        return url;

        }

}


Now we want to load properties file while load the class, then

@Configuration 

@ComponentScan

@PropertySource("classpath:app.properties")

public class SpringFrameworkProperties{

  public void main(String[] args){

  AnnotationConfigApplicationContext context = new         AnnotationConfigApplicationContext(SpringFrameworkProperties.class);

   ExternalService service= context.getBean(ExternalService.class);

System.out.println(service.getUrl());

  }

}

Friday, September 17, 2021

Why @Controller,@Service and @Repository are used in spring?

We already know that if we use @Component annotation we can easily identify bean in the IOC container .Then why need to use these special annotation-

@Controller: In MVC pattern @Controller annotation used to define servlet to serve for a http request. 

@Repository :   @Repository is the special annotation for encapsulation storage, retrieval and search behavior on relational database . Their may be any exception while operating certain operation in database but some of them can be handled by using @Repositoy annotation.

@Service:   @Service annotation is used to define business layer in spring .

Specifically annotations are categorized to apply logic on them . Using AOP we can provide special logic on the annotation .

Wednesday, September 15, 2021

In javascript how a function can return another function?

 In javascript function is object .So function can return another function .Example is below-

function interviewQuestion(job) {

    if (job === "engineer") {

        return function (name) { //annonymous function

            console.log(name + " can you please explain what is engineering");

        }

    } else if (job === "designer") {

        return function (name) {

            console.log(name + " how to design good UX");

        }

    } else {

        return function (name) {

            console.log(name + " don't be unemployed");

        }

    }

}

var question = interviewQuestion("engineer");// var question store the function expression .then                                                                                  called it.

question("lokman");

Difference between Bean factory and Application context

Bean factory and Application context both are IOC container. But there some differences between them, 

Bean factory:   Bean factory provides basic management for bean and wiring of dependencies.

Application context:  Application context is beanfactory++. Not only provides basic management and wiring of dependencies but also provides Spring AOP features. WebApplication context for web applications ,provides internationalizations.

It is recommends to use Application context in most of the enterprise Application development .

Tuesday, September 14, 2021

Example of function taking function as arguments.

 var year=[1990,1965,1970,1980];

function arrayCalc(arr,fn){

    var res=[];

    for(var i=0;i<arr.length;i++){

        res.push(fn(arr[i]))

    }

    return res;

}

function calculateAge(el){

    return 2021-el;

}

var result=arrayCalc(year,calculateAge);//here calculateAge is the callback function .

console.log(result);


Functions are also object in javascript.

 --A function is an instance of object type.

--A function behaves like any other object.

--We can store function in a variable.

--We can pass a function as argument to a function .

--We can return a function from a function .

Monday, September 13, 2021

@PostConstruct and @Predestroy

 @PostConstruct:  As soon as the bean is created and all the dependency is injected then @PostConstruct would be called.

@PreDestroy: As soon as the bean is removed from the container @Predestroy method is called. We can use where we need to release resources by the bean .


Sunday, September 12, 2021

Bean scope-

 By default bean scope is singleton that means every time we get a bean from ioc container will give me the copy of a bean .so beans are the same object.

But if we want to get different beans every time from the ioc container we should use prototype . 

To define a prototype bean we can use @Scope("prototype")/@ConfigurableBeanFactory.SCOP_PROTOTYPE

ex:


What if there is multiple implementation of a interface which is using in @Autowired ?

If there is multiple implementation of an interface then we need to specify which one's implementation will use. For that reason we need to specify @Primary in the implemented class or we can use autowired by name .But @Primary annotation have the highest precedence than autowired by name.

Another approach is we can use @Qualifier("name") over the name of the implement class .We then should use this @Qualifier("name") over the injected interface.

DI(dependency injection) using example

 Suppose we have a controller ,which accepts the request  and will response , but it depends on business layer.

@Controller

public class TodoController{

@Autowired

TodoBusinessService todoBusinessService;

}

TodoBusinessService depends to another dependency to fetch data from the database,

@Component

public class TodoBusinessService{

@Autowired

TodoDataService todoDataService;

}

now TodoDataService need to fire a query to fetch data from the database .So it depends on JdbcTemplate.

@Component

public class TodoDataService {

@Autowired

JdbcTemplate jdbcTemplate;

}

Saturday, September 11, 2021

Another ways to create object using Object.create()

 showing object creating using Object.create() using the following example,

var personProto={

    calculateAge:function(){

        console.log(2021-this.yearOfBirth);

    }

}

var john = Object.create(personProto);

john.name="john smith";

john.yearOfBirth=1989;

john.job = "engineer";


console.log(john);

john.calculateAge();

here ,personProto is a prototype which i am using to create an object,

var john = Object.create(personProto);

we first create john object then we define properties.

Another way to create an object-

var john = Object.create(personProto, {

    name: {

        value: "john"

    },

    yearOfBirth: {

        value: 1989

    },

    job: {

        value: "engineer"

    }

});

john.calculateAge();

the difference with function constructor is that , we inherit the property when we creating the object .


How objects are created using function constructor?

 lets have an example ,

var Person = function (name, roll, department) {

    this.name = name;

    this.roll = roll;

    this.dept = department;

}

Person.prototype.calculateTotalMarks = function (bangla, english) {

    console.log(bangla + english);

}

var john = new Person("john", 1, "cse");

console.log(john);

john.calculateTotalMarks(50, 50);

var jack = new Person("jack", 2, "eee");

console.log(jack);

jack.calculateTotalMarks(10, 20);

john.calculateTotalMarks(10 , 5);


In the above example Person is the function constructor . Whenever we create our own object john we use new operator which will create an empty object. then function constructor Person will call. We already know in regular function call a new execution context will create and this will point to global object (Window). but by using new operator it will point to our empty object and assign property to our object.

we can declare a method inside function constructor which can be called by the object created using function constructor. But problem is that every object will have a copy of the function . We already know we can inherit method of property inside function prototype.So, we can put method / property in constructor functions property to inherit .

thats why we put that lines,

Person.prototype.calculateTotalMarks = function (bangla, english) {

    console.log(bangla + english);

}

then every object of this constructor function will call that method.

john.calculateTotalMarks(20,30);

Wednesday, September 8, 2021

Inheritance in javascript

 


javascript is a prototype based programming language that means inheritance is possible by using prototype.Every object has this prototype property .

How Inheritance works behind the scene?

Every js object has a prototype property .If any object want to inherit the property /method then these method and property will store in prototype property .Here the person prototype  property is the prototype of john .



By default person constructor's  biggest constructor is object.
In this fig person object can inherit the prototype of object and john can access the property of person prototype and object prototype.

Constructor and instances in javascript

 


Constructor is the blueprint to create object .Here person is the constructor from which we can create objects. jane,mark and john are the 3 instances of person constructor.

Object in javascript

 


Object is use to store data,make code cleaner and structure code.

Tuesday, September 7, 2021

what 3 things need to tell spring ?

 1.what are the bean:-we annotate classes with @Component to specify our bean.

2.What are the dependencies of a bean:-We can annotate with @Autowired to specify dependencies.

3.Where to search for bean:-That means in which package beans are available .

we can specify through @ComponentScan annotation.

In spring boot @SpringBootApplication annotation automatically scan for beans in the package and sub-packages in which package this annotation reside.

--Application context: Application context is the spring container where all the beans are managed .We get beans from application context.

To check what is happening in background-

we can put logger in application.properties file as follows-

looging.level.org.springframework=debug



How events are processed?

 




An event can happen as soon as execution stack is empty. That means all the function have returned.

All the events resides in message queue in browser engine and waiting to be processed.

Since event listener is a function it put on top of execution stack and become the active execution context.

How to access DOM object?

 We can access dom object by querySelector with id in css.

ex:document.querySelector('#score').textContent=100;

 We can access dom object by querySelector with class in css.

ex:document.querySelector('.score').textContent=100;

here ,.score is the class name in css.

if we want to set any html in any html then we use innerHtml.

ex:document.querySelector('.score').textContent='<em>'+100+'</em>';

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...