Friday, August 23, 2019

ECMAScript 6 modules


In the new version of JavaScript, ECMAScript 6 (also known as ES6), native modules have been introduced. Thefollowing points are some of the most important aspects of these modules:
  • Module code always automatically runs in strict mode
  • Variables that are created in the top level of a module are not added to the global scope
  • A module must export anything that should be available to the outside code
  • A module can import bindings (things that are exported from other modules)
The main idea behind modules in ES6 is to give you complete control over what is accessible to the outside code from inside the module, as well as when the code inside of the module is executed.
Let's have a look at a simple example of an ES6 module.

Defining an ES6 module

We can define an ES6 module either inside of a .js file, or inside a 

CommonJS



CommonJS

As with AMD format, CommonJS (also known as CJS) is another format which defines JavaScript modules as objects that can be made available to any dependent code. CJS modules can only define objects, as opposed to AMD modules, which can define constructors and functions too.
Unlike AMD format, which takes a browser-first approach, CommonJS takes a server-first approach. It also covers a broader set of concerns which are server-related, such as io, file system, and alike.
Many developers (I'm one of them) use AMD format for browser-targeted modules and CommonJS for server-side targeted modules. However, you could use CJS format for browser modules as well.
Some of the tools that support CJS for the browsers are:
Let's have a look at a simple example to see how we can implement a CJS format module.

Implementing a CommonJS module

Imagine that we have a file called moduleOne.js. From inside this file, we can export...

AMD

Introducing Asynchronous Module Definition

Asynchronous Module Definition (AMD) format for creating modules in JavaScript, is targeted for use in browsers. This format proposes a particular way for defining modules so that modules and their dependencies can be loaded into the browser asynchronously.
There are two key methods that you need to use when creating and consuming AMD modules, these are defineand require methods.
The idea is that we create a module using the global define method and then we can import that module in other parts of the code (other modules) using the global require method.

Defining modules using AMD format

Here is how a module can be defined in AMD format:
define('moduleOneId', ['dependency'], function(dependency) {

    return {
        sayHi: function(){
            console.log('Hi there!')
        }
    }
});
In the preceding code, we are passing three arguments to the global define method, which has been provided to us by an AMD-compatible module loader.

https://subscription.packtpub.com/book/web_development/9781785880650/10/ch10lvl1sec54/introducing-asynchronous-module-definition

Tuesday, August 20, 2019

Difference Between Dapper and ADO .Net

ADO.NET, for example, won't give you objects (or, at best, will only give you a pseudo object like a DataTable) While Dapper allow to work with classes. Dapper is a wrapper on ADO .net

public class ADONET : ITestSignature
{
    public long GetPlayerByID(int id)
    {
        Stopwatch watch = new Stopwatch();
        watch.Start();
        using(SqlConnection conn = new SqlConnection(Constants.ConnectionString))
        {
            conn.Open();
            using(SqlDataAdapter adapter = new SqlDataAdapter("SELECT Id, FirstName, LastName, DateOfBirth, TeamId FROM Player WHERE Id = @ID", conn))
            {
                adapter.SelectCommand.Parameters.Add(new SqlParameter("@ID", id));
                DataTable table = new DataTable();
                adapter.Fill(table);
            }
        }
        watch.Stop();
        return watch.ElapsedMilliseconds;
    }

}

public class Dapper : ITestSignature
{
    public long GetPlayerByID(int id)
    {
        Stopwatch watch = new Stopwatch();
        watch.Start();
        using (SqlConnection conn = new SqlConnection(Constants.ConnectionString))
        {
            conn.Open();
            var player = conn.Query("SELECT Id, FirstName, LastName, DateOfBirth, TeamId FROM Player WHERE Id = @ID", new{ ID = id});
        }
        watch.Stop();
        return watch.ElapsedMilliseconds;
    }
}

Entityframework vs Dapper






Entity Framework (EF) and Dapper both are object-relational mappers that enable .NET developers to work with relational data using domain-specific objects. Dapper owns the title of King of Micro ORM in terms of performance.

"Micro-ORMs" like Dapper.NET (which is used on the StackExchange family of sites including StackOverflow) which promise performance at the cost of maintainability.
 The major drawback to using Dapper.NET is that you have naked SQL queries in your code.

Entity Framework

Advantages

  • Entity Framework allows you to create a model by writing code or using boxes and lines in the EF Designer and generate a new database.
  • You can write code against the Entity Framework, and the system will automatically produce objects for you as well as track changes on those objects and simplify the process of updating the database.
  • One common syntax (LINQ) for all object queries whether it is a database or not and pretty fast if used as intended, easy to implement and less coding required to accomplish complex tasks.
  • The EF can replace a large chunk of code you would otherwise have to write and maintain yourself.
  • It provides auto-generated code
  • It reduces development time and cost.
  • It enables developers to visually design models and mapping of database

Disadvantages

  • You have to think in a non-traditional way of handling data, not available for every database.
  • If there is any schema change in database FE won't work and you have to update the schema in solution as well.
  • The EF queries are generated by the provider that we cannot control.
  • It is not good for a huge domain model.
  • Lazy loading is the main drawbacks of EF

Dapper

Advantages

  • Dapper make it easy to correctly parameterize queries
  • It can easily execute queries (scalar, multi-rows, multi-grids, and no-results)
  • Make it easy to turn results into objects
  • It is very efficient and owns the title of King of Micro ORM in terms of performance.

Disadvantages

  • Dapper can't generate a class model for you
  • It cannot generate queries for you
  • It cannot track objects and their changes
  • The raw dapper library doesn't provide CRUD features, but the "contrib" additional package does provide basic CRUD.



Webpack Working

Promise Chaining

A handler, used in .then(handler) may create and return a promise.

In that case further handlers wait till it settles, and then get its result.

For instance:












new Promise(function(resolve, reject) {

  setTimeout(() => resolve(1), 1000);

}).then(function(result) {

  alert(result); // 1

  return new Promise((resolve, reject) => { // (*)
    setTimeout(() => resolve(result * 2), 1000);
  });

}).then(function(result) { // (**)

  alert(result); // 2

  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(result * 2), 1000);
  });

}).then(function(result) {

  alert(result); // 4

});
Here the first .then shows 1 and returns new Promise(…) in the line (*). After one second it resolves, and the result (the argument of resolve, here it’s result * 2) is passed on to handler of the second .then. That handler is in the line (**), it shows 2 and does the same thing.

Sunday, August 18, 2019

Software Archiect Questions


A software architect is a software expert who makes high-level design choices and dictates technical standards, including software coding standards, tools, and platforms. Software architecture refers to the high level structures of a software system, the discipline of creating such structures, and the documentation of these structures.

Q1: What does “program to interfaces, not implementations” mean?

Topic: Design Patterns
Difficulty: ⭐⭐⭐
Coding against interface means, the client code always holds an Interface object which is supplied by a factory.
Any instance returned by the factory would be of type Interface which any factory candidate class must have implemented. This way the client program is not worried about implementation and the interface signature determines what all operations can be done.
This approach can be used to change the behavior of a program at run-time. It also helps you to write far better programs from the maintenance point of view.
🔗Source: tutorialspoint.com

Q2: What are the differences between continuous integration, continuous delivery, and continuous deployment?

Topic: DevOps
Difficulty: ⭐⭐⭐
  • Developers practicing continuous integration merge their changes back to the main branch as often as possible. By doing so, you avoid the integration hell that usually happens when people wait for release day to merge their changes into the release branch.
  • Continuous delivery is an extension of continuous integration to make sure that you can release new changes to your customers quickly in a sustainable way. This means that on top of having automated your testing, you also have automated your release process and you can deploy your application at any point of time by clicking on a button.
  • Continuous deployment goes one step further than continuous delivery. With this practice, every change that passes all stages of your production pipeline is released to your customers. There's no human intervention, and only a failed test will prevent a new change to be deployed to production.
🔗Source: atlassian.com

Q3: What does SOLID stand for? What are its principles?

Topic: Software Architecture
Difficulty: ⭐⭐⭐
S.O.L.I.D is an acronym for the first five object-oriented design (OOD) principles by Robert C. Martin.
  • S - Single-responsiblity principle. A class should have one and only one reason to change, meaning that a class should have only one job.
  • O - Open-closed principle. Objects or entities should be open for extension, but closed for modification.
  • L - Liskov substitution principle. Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.
  • I - Interface segregation principle. A client should never be forced to implement an interface that it doesn't use or clients shouldn't be forced to depend on methods they do not use.
  • D - Dependency Inversion Principle. Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions.
🔗Source: scotch.io

Q4: What Is BASE Property Of A System?

Topic: Software Architecture
Difficulty: ⭐⭐⭐⭐
BASE properties are the common properties of recently evolved NoSQL databases. According to CAP theorem, a BASE system does not guarantee consistency. This is a contrived acronym that is mapped to following property of a system in terms of the CAP theorem:
  • Basically available indicates that the system is guaranteed to be available
  • Soft state indicates that the state of the system may change over time, even without input. This is mainly due to the eventually consistent model.
  • Eventual consistency indicates that the system will become consistent over time, given that the system doesn't receive input during that time.
🔗Source: fromdev.com

Q5: What Is CAP Theorem?

Topic: Software Architecture
Difficulty: ⭐⭐⭐⭐⭐
The CAP Theorem for distributed computing was published by Eric Brewer. This states that it is not possible for a distributed computer system to simultaneously provide all three of the following guarantees:
  1. Consistency (all nodes see the same data even at the same time with concurrent updates )
  2. Availability (a guarantee that every request receives a response about whether it was successful or failed)
  3. Partition tolerance (the system continues to operate despite arbitrary message loss or failure of part of the system)
The CAP acronym corresponds to these 3 guarantees. This theorem has created the base for modern distributed computing approaches. Worlds most high volume traffic companies (e.g. Amazon, Google, Facebook) use this as basis for deciding their application architecture. Its important to understand that only two of these three conditions can be guaranteed to be met by a system.
🔗Source: fromdev.com

Q6: Do you familiar with The Twelve-Factor App principles?

Topic: Software Architecture
Difficulty: ⭐⭐⭐⭐⭐
The Twelve-Factor App methodology is a methodology for building software as a service applications. These best practices are designed to enable applications to be built with portability and resilience when deployed to the web.
  • Codebase - There should be exactly one codebase for a deployed service with the codebase being used for many deployments.
  • Dependencies - All dependencies should be declared, with no implicit reliance on system tools or libraries.
  • Config - Configuration that varies between deployments should be stored in the environment.
  • Backing services All backing services are treated as attached resources and attached and detached by the execution environment.
  • Build, release, run - The delivery pipeline should strictly consist of build, release, run.
  • Processes - Applications should be deployed as one or more stateless processes with persisted data stored on a backing service.
  • Port binding - Self-contained services should make themselves available to other services by specified ports.
  • Concurrency - Concurrency is advocated by scaling individual processes.
  • Disposability - Fast startup and shutdown are advocated for a more robust and resilient system.
  • Dev/Prod parity - All environments should be as similar as possible.
  • Logs - Applications should produce logs as event streams and leave the execution environment to aggregate.
  • Admin Processes - Any needed admin tasks should be kept in source control and packaged with the application.
🔗Source: 12factor.net

Q7: What are Heuristic Exceptions?

Topic: Software Architecture
Difficulty: ⭐⭐⭐⭐⭐
A Heuristic Exception refers to a transaction participant’s decision to unilaterally take some action without the consensus of the transaction manager, usually as a result of some kind of catastrophic failure between the participant and the transaction manager.
In a distributed environment communications failures can happen. If communication between the transaction manager and a recoverable resource is not possible for an extended period of time, the recoverable resource may decide to unilaterally commit or rollback changes done in the context of a transaction. Such a decision is called a heuristic decision. It is one of the worst errors that may happen in a transaction system, as it can lead to parts of the transaction being committed while other parts are rolled back, thus violating the atomicity property of transaction and possibly leading to data integrity corruption.
Because of the dangers of heuristic exceptions, a recoverable resource that makes a heuristic decision is required to maintain all information about the decision in stable storage until the transaction manager tells it to forget about the heuristic decision. The actual data about the heuristic decision that is saved in stable storage depends on the type of recoverable resource and is not standardized. The idea is that a system manager can look at the data, and possibly edit the resource to correct any data integrity problems.
🔗Source: jboss.org

Q8: What Is Shared Nothing Architecture? How Does It Scale?

Topic: Software Architecture
Difficulty: ⭐⭐⭐⭐⭐
A shared nothing architecture (SN) is a distributed computing approach in which each node is independent and self-sufficient, and there is no single point of contention required across the system.
  • This means no resources are shared between nodes (No shared memory, No shared file storage)
  • The nodes are able to work independently without depending on each other for any work.
  • Failure on one node affects only the users of that node, however other nodes continue to work without any disruption.
This approach is highly scalable since it avoid the existence of single bottleneck in the system. Shared nothing is recently become popular for web development due to its linear scalability. Google has been using it for long time.
In theory, A shared nothing system can scale almost infinitely simply by adding nodes in the form of inexpensive machines.
🔗Source: fromdev.com

Q9: What Does Eventually Consistent Mean?

Topic: Software Architecture
Difficulty: ⭐⭐⭐⭐⭐
Unlike relational database property of Strict consistency, eventual consistencyproperty of a system ensures that any transaction will eventually (not immediately) bring the database from one valid state to another. This means there can be intermediate states that are not consistent between multiple nodes.
Eventually consistent systems are useful at scenarios where absolute consistency is not critical. For example in case of Twitter status update, if some users of the system do not see the latest status from a particular user its may not be very devastating for system.
Eventually consistent systems can not be used for use cases where absolute/strict consistency is required. For example a banking transactions system can not be using eventual consistency since it must consistently have the state of a transaction at any point of time. Your account balance should not show different amount if accessed from different ATM machines.
https://dev.to/aershov24/9-software-architecture-interview-questions-and-answers-31e7

Scalability

Scalability is the ability of a program to scale. For example, if you can do something on a small database (say less than 1000 records), a program that is highly scalable would work well on a small set as well as working well on a large set (say millions, or billions of records).


HCL

What is GOD object?
What is Cohesion and Coupling
What is the architecuter of angular?
Angular Architechture
Anguar vs MVC
What you ask client if designing a web api
Promise chaining
Event loop
Where the click event will goes in web api or call stack
Why angular is best in comparison of mvc
How to design Uber
How design web api for crud for one table
Print 1 bilion number on console
What webpack does



Cohesion and Coupling


Coupling - A measure of how much a module (package, class, method) relies on other modules. It is desirable to reduce coupling, or reduce the amount that a given module relies on the other modules of a system.


Cohesion - A measure of how closely related the members (classes, methods, functionality within a method) of a module are to the other members of the same module. It is desirable to increase cohesion as that indicates that a module has a very specific task and does only that task.


Cohesion is the indication of the relationship within module.
Coupling is the indication of the relationships between modules.

Cohesion shows the module’s relative functional strength.
Coupling shows the relative independence among the modules.

Cohesion is a degree (quality) to which a component / module focuses on the single thing.
Coupling is a degree to which a component / module is connected to the other modules.

While designing you should strive for high cohesion i.e. a cohesive component/ module focus on a single task (i.e., single-mindedness) with little interaction with other modules of the system.
While designing you should strive for low coupling i.e. dependency between modules should be less.

Cohesion is the kind of natural extension of data hiding for example, class having all members visible with a package having default visibility.
Making private fields, private methods and non public classes provides loose coupling.

Cohesion is Intra – Module Concept.
Coupling is Inter -Module Concept.



Cohesion describe a structure inside a module.
Coupling describe a relationship between multi modules.

Followers

Link