Skip to content

Commit 77f8955

Browse files
authored
Merge pull request #4 from Real001/feature/solid_translate
Translate SOLID is done
2 parents 02e2002 + 1ff4461 commit 77f8955

File tree

1 file changed

+54
-32
lines changed

1 file changed

+54
-32
lines changed

README.md

Lines changed: 54 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1443,7 +1443,7 @@ class Square implements Shape {
14431443

14441444
### Классы должны быть маленькими
14451445

1446-
Размер класса измеряется его ответственностью. Following the *Single Responsibility principle* a class should be small.
1446+
Размер класса измеряется его ответственностью. Следуя *Принципу единственной ответственности* класс должен быть маленьким.
14471447

14481448
**Плохо:**
14491449

@@ -1485,12 +1485,12 @@ class Dashboard {
14851485

14861486
### Высокая сплоченность низкая связь
14871487

1488-
Cohesion defines the degree to which class members are related to each other. Ideally, all fields within a class should be used by each method.
1489-
We then say that the class is *maximally cohesive*. In practice, this however is not always possible, nor even advisable. You should however prefer cohesion to be high.
1488+
Сплоченность определяет степень, в которой члены класса связаны друг с другом. В идеале все поля в классе должны
1489+
использоваться каждым методом. Мы говорим, что класс *максимально связный*. На практике это, однако, не всегда возможно
1490+
и даже не желательно. Однако вы должны добиваться, того чтобы сплоченность была высокой.
14901491

1491-
Coupling refers to how related or dependent are two classes toward each other. Classes are said to be low coupled if changes in one of them doesn't affect the other one.
1492-
1493-
Good software design has **high cohesion** and **low coupling**.
1492+
Соединение относится и к тому, как связаны или зависимы два класса друг от друга. Классы считаются слабосвязанными если
1493+
изменения в одном из них не влияют на другой.
14941494

14951495
**Плохо:**
14961496

@@ -1565,15 +1565,19 @@ class UserNotifier {
15651565

15661566
### Предпочитайте композицию наследованию
15671567

1568-
As stated famously in [Design Patterns](https://en.wikipedia.org/wiki/Design_Patterns) by the Gang of Four, you should *prefer composition over inheritance* where you can. There are lots of good reasons to use inheritance and lots of good reasons to use composition. The main point for this maxim is that if your mind instinctively goes for inheritance, try to think if composition could model your problem better. In some cases it can.
1568+
Как сказано в [Design Patterns](https://en.wikipedia.org/wiki/Design_Patterns) от банды черытех в должны
1569+
*Предпочитать композицию наследованию* где можете. Есть много веских причин использовать наследование и много хороших
1570+
причин использовать композицию. Суть этого принципа в том, что если ваш ум инстинктивно идет на наследование,
1571+
попробуйте подумать, может ли композиция лучше смоделировать вашу проблему. В некоторых случаях может.
15691572

1570-
You might be wondering then, "when should I use inheritance?" It depends on your problem at hand, but this is a decent list of when inheritance makes more sense than composition:
1573+
Тогда вы можете спросить: "Когда я должен использовать наследование?" Это зависит от вашей проблемы, но это достойный
1574+
список, когда наследование имеет больше смысла, чем композиция:
15711575

1572-
1. Your inheritance represents an "is-a" relationship and not a "has-a" relationship (Human->Animal vs. User->UserDetails).
1576+
1. Ваше наследование представляет собой "is-a" отношения а не "has-a" отношения (Human->Animal vs. User->UserDetails).
15731577

1574-
2. You can reuse code from the base classes (Humans can move like all animals).
1578+
2. Вы можете повторно использовать код из базовых классов (Люди могут двигаться как все животные).
15751579

1576-
3. You want to make global changes to derived classes by changing a base class. (Change the caloric expenditure of all animals when they move).
1580+
3. Вы хотите внести глобальные изменения в производные классы, изменив базовый класс. (Изменение расхода калорий у всех животных при их перемещении).
15771581

15781582
**Плохо:**
15791583

@@ -1632,9 +1636,10 @@ class EmployeeTaxData {
16321636

16331637
**[⬆ back to top](#содержание)**
16341638

1635-
### Используйте метод цепочки
1639+
### Используйте цепочки методов
16361640

1637-
This pattern is very useful and commonly used in many libraries. It allows your code to be expressive, and less verbose. For that reason, use method chaining and take a look at how clean your code will be.
1641+
Этот паттеррн очень полезен и обычно используется во многих библиотеках. Это позволяет вашему коду быть выразительным
1642+
и менее многословным. По этой причине используйте цепочку методов и посмотрите, насколько чистым будет ваш код.
16381643

16391644
**Плохо:**
16401645

@@ -1718,7 +1723,10 @@ const query = new QueryBuilder()
17181723

17191724
### Принцип единой ответственности (SRP)
17201725

1721-
As stated in Clean Code, "There should never be more than one reason for a class to change". It's tempting to jam-pack a class with a lot of functionality, like when you can only take one suitcase on your flight. The issue with this is that your class won't be conceptually cohesive and it will give it many reasons to change. Minimizing the amount of times you need to change a class is important. It's important because if too much functionality is in one class and you modify a piece of it, it can be difficult to understand how that will affect other dependent modules in your codebase.
1726+
Как написано в Чистом Коде, "Должна быть лишь одна причина для изменения класса". аманчиво представить себе класс,
1727+
переполненный большим количеством функционала, словно в полет вам позволили взять всего один чемодан. Проблема в том, что
1728+
ваш класс не будет концептуально связан, и вы будете часто его изменять. Очень важно минимизировать изменения в классе.
1729+
Когда вы вносите изменения в класс с огромным функционалом, тяжело отследить последствия ваших изменений.
17221730

17231731
**Плохо:**
17241732

@@ -1771,7 +1779,9 @@ class UserSettings {
17711779

17721780
### Принцип открытости/закрытости (OCP)
17731781

1774-
As stated by Bertrand Meyer, "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." What does that mean though? This principle basically states that you should allow users to add new functionalities without changing existing code.
1782+
Как заявил Бертран Мейер, "программные сущности (классы, модули, функции и т.д.) должны оставаться открытыми для
1783+
расширения, но закрытыми для модификации." Что это означает на практике? Принцип закрепляет, что вы должны позволить
1784+
пользователям добавлять новые функциональные возможности, но без изменения существующего кода.
17751785

17761786
**Плохо:**
17771787

@@ -1799,20 +1809,20 @@ class HttpRequester {
17991809
async fetch<T>(url: string): Promise<T> {
18001810
if (this.adapter instanceof AjaxAdapter) {
18011811
const response = await makeAjaxCall<T>(url);
1802-
// transform response and return
1812+
// трансформируем ответ и возвращаем
18031813
} else if (this.adapter instanceof NodeAdapter) {
18041814
const response = await makeHttpCall<T>(url);
1805-
// transform response and return
1815+
// трансформируем ответ и возвращаем
18061816
}
18071817
}
18081818
}
18091819

18101820
function makeAjaxCall<T>(url: string): Promise<T> {
1811-
// request and return promise
1821+
// запрос и возвращение промиса
18121822
}
18131823

18141824
function makeHttpCall<T>(url: string): Promise<T> {
1815-
// request and return promise
1825+
// запрос и возвращение промиса
18161826
}
18171827
```
18181828

@@ -1822,7 +1832,7 @@ function makeHttpCall<T>(url: string): Promise<T> {
18221832
abstract class Adapter {
18231833
abstract async request<T>(url: string): Promise<T>;
18241834

1825-
// code shared to subclasses ...
1835+
// общий код для подклассов ...
18261836
}
18271837

18281838
class AjaxAdapter extends Adapter {
@@ -1831,7 +1841,7 @@ class AjaxAdapter extends Adapter {
18311841
}
18321842

18331843
async request<T>(url: string): Promise<T>{
1834-
// request and return promise
1844+
// запрос и возвращение промиса
18351845
}
18361846

18371847
// ...
@@ -1843,7 +1853,7 @@ class NodeAdapter extends Adapter {
18431853
}
18441854

18451855
async request<T>(url: string): Promise<T>{
1846-
// request and return promise
1856+
// запрос и возвращение промиса
18471857
}
18481858

18491859
// ...
@@ -1855,7 +1865,7 @@ class HttpRequester {
18551865

18561866
async fetch<T>(url: string): Promise<T> {
18571867
const response = await this.adapter.request<T>(url);
1858-
// transform response and return
1868+
// трансформируем ответ и возвращаем
18591869
}
18601870
}
18611871
```
@@ -1864,9 +1874,14 @@ class HttpRequester {
18641874

18651875
### Принцип подстановки Лисков (LSP)
18661876

1867-
This is a scary term for a very simple concept. It's formally defined as "If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.)." That's an even scarier definition.
1877+
Это страшный термин для очень простой концепции. Формальным языком он звучит как "Если S является подтипом T, то
1878+
объекты типа Т могут быть заменены на объекты типа S (то есть, объекты типа S могут заменить объекты типа Т) без влияния
1879+
на важные свойства программы (корректность, пригодность для выполнения задач и т.д.)." Это еще более страшное определение.
18681880

1869-
The best explanation for this is if you have a parent class and a child class, then the parent class and child class can be used interchangeably without getting incorrect results. This might still be confusing, so let's take a look at the classic Square-Rectangle example. Mathematically, a square is a rectangle, but if you model it using the "is-a" relationship via inheritance, you quickly get into trouble.
1881+
Лучшее объяснение заключается в том, что если у вас есть родительский и дочерний классы, то они могут использоваться как
1882+
взаимозаменяемые, не приводя при этом к некорректным результатам. Это по-прежнему может сбивать с толку, так что давайте
1883+
взглянем на классический пример квадрата-прямоугольника. Математически квадрат представляет собой прямоугольник, но если
1884+
вы смоделируете их отношения через наследование, вы быстро наткнетесь на неприятности..
18701885

18711886
**Плохо:**
18721887

@@ -1981,8 +1996,11 @@ renderLargeShapes(shapes);
19811996

19821997
### Принцип разделения интерфейса (ISP)
19831998

1984-
ISP states that "Clients should not be forced to depend upon interfaces that they do not use.". This principle is very much related to the Single Responsibility Principle.
1985-
What it really means is that you should always design your abstractions in a way that the clients that are using the exposed methods do not get the whole pie instead. That also include imposing the clients with the burden of implementing methods that they don’t actually need.
1999+
ISP говорит что "Клиенты не должны зависеть от классов, которые они не используют.". Этот принцип очень
2000+
связан с Принципом единой ответственности.
2001+
На самом деле это означает, что вы всегда должны проектировать свои абстракции таким образом, чтобы клиенты, которые
2002+
используют открытые методы не получали весь пирог. Это также включает в себя возложение на клиентов бремени реализации
2003+
методов, которые им на самом деле не нужны.
19862004

19872005
**Плохо:**
19882006

@@ -2062,15 +2080,19 @@ class EconomicPrinter implements Printer {
20622080

20632081
### Принцип инверсии зависимостей (DIP)
20642082

2065-
This principle states two essential things:
2083+
Этот принцип закрепляет две важные вещи:
20662084

2067-
1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
2085+
1. Модули высшего уровня не должны зависеть от модулей низшего уровня. Оба должны зависеть от абстракций.
20682086

2069-
2. Abstractions should not depend upon details. Details should depend on abstractions.
2087+
2. Абстракции не должны зависеть от деталей. Детали должны зависеть от абстракций.
20702088

2071-
This can be hard to understand at first, but if you've worked with Angular, you've seen an implementation of this principle in the form of Dependency Injection (DI). While they are not identical concepts, DIP keeps high-level modules from knowing the details of its low-level modules and setting them up. It can accomplish this through DI. A huge benefit of this is that it reduces the coupling between modules. Coupling is a very bad development pattern because it makes your code hard to refactor.
2089+
Сначала трудно понять этот принцип. Но если вы работали с AngularJS, вы видели реализацию этого принципа в виде
2090+
Dependency Injection (DI). Несмотря на то, что они не являются идентичными понятиями, DIP даёт возможность отграничить
2091+
модули высокого уровня от деталей модулей низкого уровня и установки их. Он может сделать это через DI. Этот принцип
2092+
уменьшает связь между модулями. Если ваши модули тесно связаны, их тяжело рефакторить.
20722093

2073-
DIP is usually achieved by a using an inversion of control (IoC) container. An example of a powerful IoC container for TypeScript is [InversifyJs](https://www.npmjs.com/package/inversify)
2094+
DIP обычно достигается использованием контейнера инверсии управления (IoC). Пример мощного контейнера IoC для
2095+
TypeScript это [InversifyJs](https://www.npmjs.com/package/inversify)
20742096

20752097
**Плохо:**
20762098

0 commit comments

Comments
 (0)