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: architecture/design-patterns.md
+7-11
Original file line number
Diff line number
Diff line change
@@ -1,16 +1,12 @@
1
-
## Паттерны проектирования (Design Patterns)
1
+
## Design Patterns
2
2
3
-
Паттерны нужны только там, где они уместны. У каждого паттерна есть собственная цель и область применения.
4
-
Если нет точной уверенности что использование паттерна решит проблему масштабирования приложения, то и использование его не рекомендуется.
3
+
Patterns are only necessary where they are appropriate. Each pattern has its own goal and scope of application. If there is no certainty that the use of a pattern will solve the problem of scaling the application, then it is not recommended to use it.
5
4
6
-
Так же есть один из самых распространенных паттернов так же один из самых полезных - это фабричный метод.
7
-
Его самый важный плюс в том, что его цель отделить конкретику от общего процесса. При этом достигается инкапсуляция.
8
-
Так же соблюдается инверсия зависимостей. И реализация не уходит в излишнюю абстракцию, что сохраняет читабельность, и не делает из кода лазанью.
5
+
One of the most common and useful patterns is the Factory Method. Its main advantage is that it separates the specifics from the general process, achieving encapsulation. In addition, it adheres to the principle of Inversion of Control. Its implementation does not lead to excessive abstraction, which preserves readability and does not turn the code into a mess.
9
6
10
-
Типовая задача звучит примерно всегда одинаково: У нас есть разные сущности, которые должны иметь одинаковое поведение.
7
+
The typical problem sounds almost always the same: we have different entities that should have the same behavior.
11
8
12
-
Возьмем к примеру склад на который товар может прийти различными способами и будет различие в оприходовании, но выгружен на одном и том же складе.
13
-
Допустим нам его может привезти грузовик, или он может прийти к нам пароходом.
9
+
Let's take a warehouse, where goods can arrive in different ways and there may be differences in inventorying, but they are still stored in the same warehouse. For example, the goods can be delivered by truck or by ship.
14
10
```php
15
11
interface IArrival
16
12
{
@@ -58,6 +54,6 @@ class StockControl
58
54
}
59
55
```
60
56
61
-
Таким образом происходит деление задачи на две подзадачи. Первое определить сам товар и оприходовать его. Вторая разместить на складе.
57
+
This way, the task is divided into two subtasks. The first one is to identify the goods and receive them. The second one is to place them in the warehouse.
62
58
63
-
Так же есть разные вариации, трактования и подтипы паттернов, что привело к нарушению принципа не плодить сущности сверх необходимого.
59
+
There are also various variations, interpretations, and subtypes of patterns, which led to a violation of the principle of not creating entities beyond what is necessary.
В PHP функциональное программирование реализовано не полностью.
4
-
Но из данного подхода написания кода можно подчеркнуть самую главную концепцию - **Чистые функции**.
3
+
In PHP, functional programming is not fully implemented.
4
+
However, from this approach to writing code, the most important concept can be highlighted - **Pure functions**.
5
5
6
-
_Чистыми называют функции, которые не имеют побочных эффектов ввода-вывода и памяти (они зависят только от своих параметров и возвращают только свой результат).(с)Википедия_
6
+
_A pure function is defined as a function that has no side effects on input-output and memory (it depends only on its parameters and returns only its result). (c) Wikipedia_
7
7
8
-
В PHP есть чистые функции из коробки. К примеру`array_map`или`array_filter`. Так же есть и грязные функции к примеру `date`
8
+
In PHP, there are pure functions out of the box. For example,`array_map`or`array_filter`. There are also impure functions, such as `date`.
9
9
10
-
Чистые функции имеют огромное преимущество - предсказуемое поведение.
10
+
Pure functions have a huge advantage - predictable behavior.
Copy file name to clipboardExpand all lines: architecture/grasp.md
+12-18
Original file line number
Diff line number
Diff line change
@@ -1,23 +1,20 @@
1
-
## GRASP принципы
1
+
## GRASP
2
2
3
-
Принципы GRASP описывают как разделить правильно код на логические части так, чтоб достичь полиморфизма.
3
+
GRASP describe how to properly divide code into logical parts in order to achieve polymorphism.
4
4
5
-
Из GRASP понадобится всего один принцип для объединения(Information Expert) и два принципа для разделения логики (Low Coupling и High Cohesion).
5
+
From GRASP, only one principle will be needed for combining (Information Expert) and two principles for separating logic (Low Coupling and High Cohesion).
6
6
7
-
Начнем с разделения логики, так как зачастую в проектах без какого-либо этикета написания кода можно встретить или fat model, или fat controller.
8
-
Эти два принципа помогают как в написании нового функционала в новом проекте, так и при рефакторинге старого легаси проекта.
9
-
Руководствуясь логикой, что при создании нового функционала разработчик склонен плодить сущности сверх необходимого, а при доработке наоборот старается не создавать лишних сущностей, необходимо постараться выдерживать баланс.
7
+
Let's start with separating logic, since often in projects without any coding etiquettes, you can encounter either a fat model or a fat controller. These two principles help in both writing new functionality in a new project and refactoring old legacy projects.
8
+
9
+
Based on the logic that when creating new functionality, a developer tends to create entities beyond what is necessary, and when modifying existing code, the developer tries not to create unnecessary entities, it is necessary to try to maintain a balance.
10
10
11
11
### Low Coupling
12
12
13
-
Low Coupling (слабое зацепление) - этот принцип гласит чем меньше `use` в классе тем лучше.
14
-
Самым ярким примером слабого зацепления является антипаттерн God object.
15
-
God object может быть минимально зависим от других объектов при этом содержать в себе реализацию логики не относящуюся к данному объекту, что уменьшает высокую связанность.
13
+
Low Coupling - this principle states that the less `use` in a class, the better. The most vivid example of weak coupling is the God object antipattern. A God object can be minimally dependent on other objects while containing the implementation of logic that is not related to the given object, which reduces high cohesion.
16
14
17
15
### High Cohesion
18
16
19
-
High Cohesion (высокая связанность) - принцип диктует правило для класса. Класс должен выполнять минимальное количество действий.
20
-
К примеру если класс реализует логику рассылки писем, то этот класс не должен отвечать за формирование содержимого этого письма.
17
+
High Cohesion - the principle dictates a rule for a class. The class should perform the minimum amount of actions. For example, if a class implements the logic of sending emails, this class should not be responsible for generating the content of this email.
При помощи такого разделения `Mailer` отвечает только за отправку, но не отвечает за отправляемое, а `Mail` наоборот.
57
-
То есть изменив логику формирования письма это никак не повлияет на его отправку и наоборот, если есть необходимость поменять способ отправки не нужно будет задумываться еще и формировании его содержимого.
52
+
With this separation, `Mailer` is responsible only for sending, but not for what is being sent, and `Mail` is responsible for the content of the email. In other words, changing the logic of forming the email content will not affect its sending, and conversely, if there is a need to change the way the email is sent, there is no need to also consider how its content is formed.
58
53
59
54
### Information Expert
60
55
61
-
Information Expert - этот принцип говорит нам, что кто владеет данными, тот и должен по логике ими управлять.
56
+
Information Expert - this principle tells us that whoever owns the data should logically be the one to manage it.
62
57
63
58
```php
64
59
class BillProduct {
@@ -91,5 +86,4 @@ class Bill {
91
86
}
92
87
```
93
88
94
-
Из примера видно, что у продукта из счёта есть свойства, которые позволяют рассчитать стоимость одной позиции. Значит она и должна быть рассчитана в `BillProduct`.
95
-
А `Bill` оперирует уже всеми продуктами. Значит общая сумма по счету должна быть рассчитана в нем.
89
+
The example shows that the product in the bill has properties that allow calculating the cost of one item. Therefore, it should be calculated in `BillProduct`. `Bill`, in turn, operates with all products, so the total amount for the bill should be calculated there.
Copy file name to clipboardExpand all lines: architecture/oop.md
+15-13
Original file line number
Diff line number
Diff line change
@@ -1,11 +1,11 @@
1
-
## Объектно-ориентированное программирование
1
+
## Object-oriented programming
2
2
3
-
Цель ООП достичь полиморфизма. Полиморфизм обеспечивает масштабируемость проекта. Еще одно преимущество ООП это инкапсуляция.
3
+
The goal of OOP is to achieve polymorphism. Polymorphism provides scalability to the project. Another advantage of OOP is encapsulation.
4
4
5
-
Полиморфизм представляет собой единый сценарий обработки объектов разных экземпляров классов.
6
-
В первую очередь полиморфизма нужно добиться для классов, которые реализуют бизнес логику.
5
+
Polymorphism represents a single scenario for processing objects of different class instances.
6
+
First and foremost, polymorphism should be achieved for classes that implement business logic.
7
7
8
-
В пример можно привести формирование одного счета в кафе, где за бар и еду платим отдельно из-за разного формирования цены.
8
+
As an example, we can consider the process of creating a single bill in a cafe, where we pay separately for the bar and food due to the different pricing methods.
9
9
```php
10
10
interface IBill
11
11
{
@@ -47,13 +47,15 @@ class FullBill
47
47
}
48
48
}
49
49
```
50
-
При данной реализации добавить отдельный расчет, реализующий другую логику формирования суммы, не составит труда. Но тут так же играет роль сам бизнес процесс, который и диктует требования к реализации.
51
-
Всегда из поставленной задачи необходимо попытаться предположить как может измениться процесс. Так как можно усложнить приложение там, где никогда процесс работы не поменяется.
50
+
The goal of OOP is to achieve polymorphism, which provides scalability of the project. Another advantage of OOP is encapsulation.
52
51
53
-
Наследование является достаточно спорным решением для достижения полиморфизма из-за рисков создания God object и/или уход в излишнюю абстракцию, которая приведет к сильной зависимости(связанности) классов между собой вдобавок усложнив читабельность кода.
54
-
По возможности не используйте абстрактные классы, если не достигается полиморфизм.
52
+
Polymorphism represents a single scenario for processing objects of different class instances. Polymorphism should be achieved primarily for classes that implement business logic.
55
53
56
-
Инкапсуляция помогает же скрыть детали реализации. Зачастую чтоб отрефакторить старый код, понять его логику помогает подход реализуемый в 3 этапа:
57
-
- разделить код на логические куски.
58
-
- инкапсулировать логику этих кусков кода.
59
-
- написав по возможности unit тесты, попутно задокументировав логику работы, внести необходимые изменения.
54
+
In this implementation, adding a separate calculation that implements a different logic for calculating the sum will not be difficult. However, the business process itself also plays a role, which dictates the requirements for implementation. It is always necessary to try to anticipate how the process can change from the given task. Otherwise, it is possible to complicate the application where the work process will never change.
55
+
56
+
Inheritance is a controversial solution for achieving polymorphism due to the risks of creating a God object and/or going into excessive abstraction, which will lead to strong dependence (coupling) of classes with each other and further complicating code readability. If polymorphism is not achieved, abstract classes should not be used if possible.
57
+
58
+
Encapsulation helps to hide implementation details. Often, to refactor old code, a three-stage approach is used to understand its logic:
59
+
- divide the code into logical pieces.
60
+
- encapsulate the logic of these pieces of code.
61
+
- write unit tests if possible, documenting the logic of the work, and make the necessary changes.
0 commit comments