You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+54-32Lines changed: 54 additions & 32 deletions
Original file line number
Diff line number
Diff line change
@@ -1443,7 +1443,7 @@ class Square implements Shape {
1443
1443
1444
1444
### Классы должны быть маленькими
1445
1445
1446
-
Размер класса измеряется его ответственностью. Following the *Single Responsibility principle* a class should be small.
1446
+
Размер класса измеряется его ответственностью. Следуя *Принципу единственной ответственности* класс должен быть маленьким.
1447
1447
1448
1448
**Плохо:**
1449
1449
@@ -1485,12 +1485,12 @@ class Dashboard {
1485
1485
1486
1486
### Высокая сплоченность низкая связь
1487
1487
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
+
и даже не желательно. Однако вы должны добиваться, того чтобы сплоченность была высокой.
1490
1491
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
+
изменения в одном из них не влияют на другой.
1494
1494
1495
1495
**Плохо:**
1496
1496
@@ -1565,15 +1565,19 @@ class UserNotifier {
1565
1565
1566
1566
### Предпочитайте композицию наследованию
1567
1567
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
+
попробуйте подумать, может ли композиция лучше смоделировать вашу проблему. В некоторых случаях может.
1569
1572
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
+
список, когда наследование имеет больше смысла, чем композиция:
1571
1575
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).
1573
1577
1574
-
2.You can reuse code from the base classes (Humans can move like all animals).
1578
+
2.Вы можете повторно использовать код из базовых классов (Люди могут двигаться как все животные).
1575
1579
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.Вы хотите внести глобальные изменения в производные классы, изменив базовый класс. (Изменение расхода калорий у всех животных при их перемещении).
1577
1581
1578
1582
**Плохо:**
1579
1583
@@ -1632,9 +1636,10 @@ class EmployeeTaxData {
1632
1636
1633
1637
**[⬆ back to top](#содержание)**
1634
1638
1635
-
### Используйте метод цепочки
1639
+
### Используйте цепочки методов
1636
1640
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
+
и менее многословным. По этой причине используйте цепочку методов и посмотрите, насколько чистым будет ваш код.
1638
1643
1639
1644
**Плохо:**
1640
1645
@@ -1718,7 +1723,10 @@ const query = new QueryBuilder()
1718
1723
1719
1724
### Принцип единой ответственности (SRP)
1720
1725
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
+
Когда вы вносите изменения в класс с огромным функционалом, тяжело отследить последствия ваших изменений.
1722
1730
1723
1731
**Плохо:**
1724
1732
@@ -1771,7 +1779,9 @@ class UserSettings {
1771
1779
1772
1780
### Принцип открытости/закрытости (OCP)
1773
1781
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
+
пользователям добавлять новые функциональные возможности, но без изменения существующего кода.
1775
1785
1776
1786
**Плохо:**
1777
1787
@@ -1799,20 +1809,20 @@ class HttpRequester {
1799
1809
async fetch<T>(url:string):Promise<T> {
1800
1810
if (this.adapterinstanceofAjaxAdapter) {
1801
1811
const response =awaitmakeAjaxCall<T>(url);
1802
-
//transform response and return
1812
+
//трансформируем ответ и возвращаем
1803
1813
} elseif (this.adapterinstanceofNodeAdapter) {
1804
1814
const response =awaitmakeHttpCall<T>(url);
1805
-
//transform response and return
1815
+
//трансформируем ответ и возвращаем
1806
1816
}
1807
1817
}
1808
1818
}
1809
1819
1810
1820
function makeAjaxCall<T>(url:string):Promise<T> {
1811
-
//request and return promise
1821
+
//запрос и возвращение промиса
1812
1822
}
1813
1823
1814
1824
function makeHttpCall<T>(url:string):Promise<T> {
1815
-
//request and return promise
1825
+
//запрос и возвращение промиса
1816
1826
}
1817
1827
```
1818
1828
@@ -1822,7 +1832,7 @@ function makeHttpCall<T>(url: string): Promise<T> {
1822
1832
abstractclassAdapter {
1823
1833
abstractasync request<T>(url:string):Promise<T>;
1824
1834
1825
-
//code shared to subclasses ...
1835
+
//общий код для подклассов ...
1826
1836
}
1827
1837
1828
1838
classAjaxAdapterextendsAdapter {
@@ -1831,7 +1841,7 @@ class AjaxAdapter extends Adapter {
1831
1841
}
1832
1842
1833
1843
async request<T>(url:string):Promise<T>{
1834
-
//request and return promise
1844
+
//запрос и возвращение промиса
1835
1845
}
1836
1846
1837
1847
// ...
@@ -1843,7 +1853,7 @@ class NodeAdapter extends Adapter {
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
+
на важные свойства программы (корректность, пригодность для выполнения задач и т.д.)." Это еще более страшное определение.
1868
1880
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
+
вы смоделируете их отношения через наследование, вы быстро наткнетесь на неприятности..
1870
1885
1871
1886
**Плохо:**
1872
1887
@@ -1981,8 +1996,11 @@ renderLargeShapes(shapes);
1981
1996
1982
1997
### Принцип разделения интерфейса (ISP)
1983
1998
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
+
методов, которые им на самом деле не нужны.
1986
2004
1987
2005
**Плохо:**
1988
2006
@@ -2062,15 +2080,19 @@ class EconomicPrinter implements Printer {
2062
2080
2063
2081
### Принцип инверсии зависимостей (DIP)
2064
2082
2065
-
This principle states two essential things:
2083
+
Этот принцип закрепляет две важные вещи:
2066
2084
2067
-
1.High-level modules should not depend on low-level modules. Both should depend on abstractions.
2085
+
1.Модули высшего уровня не должны зависеть от модулей низшего уровня. Оба должны зависеть от абстракций.
2068
2086
2069
-
2.Abstractions should not depend upon details. Details should depend on abstractions.
2087
+
2.Абстракции не должны зависеть от деталей. Детали должны зависеть от абстракций.
2070
2088
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
+
уменьшает связь между модулями. Если ваши модули тесно связаны, их тяжело рефакторить.
2072
2093
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)
0 commit comments