General questions Flashcards

1
Q

Continuous Integration

A

Continuous Integration - це практика розробки програмного забезпечення, яка полягає в злитті робочих копій в основну гілку розробки кілька разів на день і виконанні частих автоматизованих збірок проекту для якнайшвидшого виявлення потенційних дефектів і рішення інтеграційних проблем.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

API

A

API – это интерфейс, который позволяет разработчикам использовать готовые блоки для построения приложения.

1) is a set of clearly defined methods of communication between various software components

In basic terms, APIs just allow applications to communicate with one another.

!! an API is “a set of functions and procedures” that allow you to access and build upon the data and functionality of an existing application.

API stands for Application Programming Interface, and it lets developers integrate any two parts of an application or any different applications together. It consists of various elements such as functions, protocols, and tools that allow developers to build applications. A common goal of all types of APIs is to accelerate the development of applications by providing a part of its functionality out-of-the-box, so developers do not have to implement it themselves. There are APIs for all types of systems, including operating systems, libraries, and the Web.

2) an API - a publicly available web-based API that returns data, likely in JSON or XML.
They allow us to go get data from outside sources.
We can send an API a request detailing the information we want.

web based APIs that return data in response to a request made by a client.

!!Nowadays, when we’re talking about APIs we’re typically referring to web APIs, which expose an application’s data and functionality over the internet. If you look closely, you’ll see that web APIs power our everyday lives:

Technically speaking, web APIs usually send data back and forth using HTTP requests. These requests often return textual data in the form of a JSON or XML response.

Например, при работе со сторонней библиотекой, идёт обращение к API этой библиотеки в своём коде для её взимодействия с остальным кодом.

В объектно-ориентированном проектировании код представлен в виде совокупности объектов. В приложении таких объектов, взаимодействующих между собой, могут быть сотни. У каждого из них есть свой API — набор публичных свойств и методов для взаимодействия с другими объектами в приложении. Объекты могут также иметь частную, внутреннюю логику, которая скрыта от окружения и не является API.

В случае веб-приложений, API может отдавать данные в отличном от стандартного HTML формате (XML или JSON чаще всего), благодаря чему им удобно пользоваться при написании собственных приложений.

Например, Github имеет свой API, которым могут воспользоваться другие разработчики. API Гитхаба позволяет, например, получать информацию о пользователе, его аватаре, читателях и т. д.

API’s provide mechanisms for CRM customers to access and manipulate data stored by the API provider (Salesforce in this example). The user makes a “request” to a Salesforce webserver, that webserver accesses a Salesforce database (with the customers data), and returns it to the requester in a “response”.
This same request/response cycle is used when you access webpages in your browser. The major difference between an “API request” and a “webpage request” is what kind of data is provided in the response. A website returns HTML, CSS, and JavaScript which work together with your browser to render a webpage. Web APIs respond with data in a raw format, not intended to be rendered by a browser into a user experience. JSON and XML are the most common formats used for this raw data, and they are both flexible text formats for storing data. Nearly all programming languages have libraries that can “parse” JSON and XML, making them friendly choices for developers.

Because a web API uses an HTTP request you can query a public API (meaning one that does not require authentication/login) directly in your browser.

Reddit has a public JSON API which delivers the “raw data” without any of the CSS, HTML, and JavaScript that is used to create a user interface.

In this case, each “child” is a post on Reddit — that fact is part of the definition of the Reddit API. Each API must define its own format for the data that it serves; developers typically read documentation provided by the API “maintainer” (Reddit in this case) in order to learn the data format and use it properly.

Many API’s are built with the intentions to allow 3rd party developers to build interesting applications using company data.

Apps that “consume” the API data are sometimes called API Integrations. For example, a product manager might ask a software engineer to “Write an API integration that consumes the Salesforce API and saves the data into our on-site analytics database.”

Because the APIs simply provide data, there are no limits on how a company can then go on to use that data.

Another benefit of Web APIs is that, because they are built around the HTTP protocol, nearly any programming language can be used to access them. Python, R, Java, JavaScript, Ruby, and every other general purpose programming language has at least one HTTP library to make this process easier.

APIs allow our sites to alter data on other applications, too. For instance, you’ve probably seen “Share on Facebook” or “Share on Twitter” buttons on miscellaneous websites. When/if you click one of these buttons, the site you’re visiting can communicate with your Facebook or Twitter account, and alter its data by adding new status or tweet.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Dependency Injection

A

Шаблон, за яким клас отримує екземпляри необхідних йому об’єктів (так званих залежностей) із зовнішнього джерела, а не створює їх сам.

В полном соответствии с принципом единственной обязанности объект отдаёт заботу о построении требуемых ему зависимостей внешнему, специально предназначенному для этого общему механизму[1].
DI framework provides declared dependencies to a class when that class is instantiated.
You can tell Angular to inject a dependency in a component's constructor by specifying a constructor parameter with the dependency type.

Якщо для service класу вказаний декоратор Injectable, вказаний екземпляр зберігається у вбудованому Angular Injector. Angular’s Injector - це контейнер, який створює та керує одним екземпляром (Singleton) кожного зареєстрованого сервісу.

There is only one root injector for an app. Providing UserService at the root or AppModule level means it is registered with the root injector. There is just one UserService instance in the entire app and every class that injects UserService gets this service instance unless you configure another provider with a child injector.

Всякий раз, коли компоненті потрібен сервіс, він вводиться в конструктор, коли компонента інстанціюється.

Якщо ми вказуємо сервіси в providers[] в декоратор NgModule eager модуля, то injector створить лише один екземпляр сервісу, навіть якщо він включений в провайдери декількох eager модулів.

Якщо ми вказуємо сервіс в providers[] lazy модуля, то його екземпляр буде створений в child injector, і якщо ми спробуємо впровадити такий сервіс в компоненту eager модуля, то отримаємо помилку.

Якщо ми вказуємо сервіс в providers[] декоратора Component, то буде створюватися новий екземпляр при кожному створенні екземпляра компоненти і знищуватися із знищенням компоненти.

З Angular 6 можна задавти в декораторі @Injectable у властивість providedIn, де буде впроваджений сервіс.
Modules can be providedIn the ‘root’ or in any of the available modules (eg providedIn: SomeModule).

The main benefit of this solution is that the services will be bundled only if they are really used. “Used” stands for being injected into some component or other service.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Eager loading

A

Eager Loading

  1. In eager loading module, feature modules are loaded before application start on the first hit. To load a feature module eagerly, we need to import that module in application module i.e. AppModule using imports metadata of @NgModule decorator.
  2. When a module is loaded, it loads all the imported modules, configured components, services, custom pipes etc.
  3. Modules are loaded in the order they are configured in imports metadata.
  4. Eager loading is good for small applications because at the first hit of the application all the modules are loaded and all the required dependencies are resolved. Now the subsequent access to the application will be faster.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Lazy Loading

A
Lazy Loading
a. When the modules are loaded on-demand, then it is called lazy loading. It is loaded by using loadChildren property in route configuration. In lazy loading, modules are loaded asynchronously. These modules must not be imported in application module otherwise they will be eagerly loaded.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Preload Loading

A

To configure preloading features modules, first we will configure them for lazy loading and then using Angular in-built PreloadAllModules strategy, we enable to load all lazy loading into preloading modules.
Using PreloadAllModules strategy, all modules configured by loadChildren property will be preloaded. The modules configured by loadChildren property will be either lazily loaded or preloaded but not both. To preload only selective modules, we need to use custom preloading strategy.

RouterModule.forRoot(routes,
{
preloadingStrategy: PreloadAllModules
})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Provider Interface

A
provider
An object that implements one of the Provider interfaces. A provider object defines how to obtain an injectable dependency associated with a DI token. An injector uses the provider to create a new instance of a dependency for a class that requires it.

Провайдер - обєкт, який каже як отримати injectable залежність повязану з DI token.

Інжектор використовує провайдер, щоб створити екземпляр залежності, для класу якому він потрібен.

The Provider object literal
The class-provider syntax is a shorthand expression that expands into a provider configuration, defined by the Provider interface. The following code snippets shows how a class that is given as the providers value is expanded into a full provider object.

content_copy
providers: [Logger]
content_copy
[{ provide: Logger, useClass: Logger }]

The expanded provider configuration is an object literal with two properties.

The provide property holds the token that serves as the key for both locating a dependency value and configuring the injector.

The second property is a provider definition object, which tells the injector how to create the dependency value. The provider-definition key can be useClass, as in the example. It can also be useExisting, useValue, or useFactory. Each of these keys provides a different type of dependency, as discussed below.

Sometimes it’s easier to provide a ready-made object rather than ask the injector to create it from a class. To inject an object you have already created, configure the injector with the useValue option.

In case when dependency injector should inject that singleton instance when a component asks for either the new or the old logger. OldLogger should be an alias for NewLogger - useExisting option.

В последнем примере DepositsService - это injection token, по которому injector идентифицирует запрашиваемый сервис. Обращение к сервисам внутри приложения происходит именно по их injection token.

Также в качестве элемента массива свойства Angular providers можно передать объект конфигурации сервиса.

providers: [{provide: DepositsService, useClass: OtherService}]

Так при обращении к DepositsService будет использован OtherService.

Возможные свойства объекта конфигурации:

useClass - каждый раз при обращении к зависимости, указанной в provide, создается новый экземпляр класса, указанного в useClass;
useExisting - каждый раз при обращении к зависимости, указанной в provide, будет использоваться один и тот же экземпляр класса, указанного в useClass;
useValue - позволяет при обращении к зависимости, указанной в provide, использовать предопределенный объект;
useFactory и deps - эти свойства позволяют создавать переопределяющее значение динамически уже в процессе работы приложения.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Subject

A

AsyncSubject - Асинхронный сабж уведомляет своих зрителей только о последнем произошедшем событии и только когда сабж успешно завершается. Если асинхронный сабж завершится ошибкой, его зрители будут уведомлены только об ошибке.

BehaviorSubject - При подписке поведенческий сабж уведомляет своего зрителя о последнем произошедшем в нём событии или, если в сабже ещё не происходило событий, создаёт для зрителя событие с изначальной информацией. Изначальная информация передаётся при создании поведенческого сабжа, в примере выше мы передаём 0 .
Важно! Поведенческий сабж имеет полезный метод .getValue() , который возвращает информацию, содержавшеюся в последнем произошедшем в сабже событии.

ReplaySubject - При подписке повторяющий сабж уведомляет своего зрителя о всех произошедшем в нём событиях с момента создания. Для увеличения производительности, мы можем ограничить количество событий, повторяющихся для каждого нового зрителя:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Curring

A

функція, яка приймає декілька аргументів, розбивається на декілька функцій, кожна з яких приймає один аргумент.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly