Skip to content

Commit 5e8e874

Browse files
committed
translated
1 parent 9a6a89d commit 5e8e874

File tree

6 files changed

+127
-143
lines changed

6 files changed

+127
-143
lines changed

architecture/design-patterns.md

+7-11
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,12 @@
1-
## Паттерны проектирования (Design Patterns)
1+
## Design Patterns
22

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.
54

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.
96

10-
Типовая задача звучит примерно всегда одинаково: У нас есть разные сущности, которые должны иметь одинаковое поведение.
7+
The typical problem sounds almost always the same: we have different entities that should have the same behavior.
118

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.
1410
```php
1511
interface IArrival
1612
{
@@ -58,6 +54,6 @@ class StockControl
5854
}
5955
```
6056

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.
6258

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.
+8-8
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
## Функциональное программирование
1+
## Functional Programming
22

3-
В 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**.
55

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_
77

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`.
99

10-
Чистые функции имеют огромное преимущество - предсказуемое поведение.
10+
Pure functions have a huge advantage - predictable behavior.
1111
```php
1212
$orderProducts = [
1313
['quantity' => 3, 'price' => 3.6],
@@ -18,6 +18,6 @@ $orderProductsSum = array_map(fn($product) => $product['quantity'] * $product['p
1818
$orderSum = array_sum($orderProductsSum);
1919
```
2020

21-
Эти функции не модифицируют входные параметры. При одинаковых входных параметров всегда на выходе один и тот же результат.
21+
These functions do not modify the input parameters. With the same input parameters, the output is always the same.
2222

23-
Данную концепцию можно перенести и на методы объектов.
23+
This concept can also be applied to object methods.

architecture/grasp.md

+12-18
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,20 @@
1-
## GRASP принципы
1+
## GRASP
22

3-
Принципы GRASP описывают как разделить правильно код на логические части так, чтоб достичь полиморфизма.
3+
GRASP describe how to properly divide code into logical parts in order to achieve polymorphism.
44

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).
66

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.
1010

1111
### Low Coupling
1212

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.
1614

1715
### High Cohesion
1816

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.
2118

2219
```php
2320
class Mail {
@@ -39,7 +36,7 @@ class Mail {
3936

4037
public function getBody()
4138
{
42-
// логика формирования письма
39+
// logic of composing the email
4340
return sprintf($this->bodyBoilerplate, $username);
4441
}
4542
}
@@ -52,13 +49,11 @@ class Mailer
5249
}
5350
}
5451
```
55-
56-
При помощи такого разделения `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.
5853

5954
### Information Expert
6055

61-
Information Expert - этот принцип говорит нам, что кто владеет данными, тот и должен по логике ими управлять.
56+
Information Expert - this principle tells us that whoever owns the data should logically be the one to manage it.
6257

6358
```php
6459
class BillProduct {
@@ -91,5 +86,4 @@ class Bill {
9186
}
9287
```
9388

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.

architecture/oop.md

+15-13
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
## Объектно-ориентированное программирование
1+
## Object-oriented programming
22

3-
Цель ООП достичь полиморфизма. Полиморфизм обеспечивает масштабируемость проекта. Еще одно преимущество ООП это инкапсуляция.
3+
The goal of OOP is to achieve polymorphism. Polymorphism provides scalability to the project. Another advantage of OOP is encapsulation.
44

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.
77

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.
99
```php
1010
interface IBill
1111
{
@@ -47,13 +47,15 @@ class FullBill
4747
}
4848
}
4949
```
50-
При данной реализации добавить отдельный расчет, реализующий другую логику формирования суммы, не составит труда. Но тут так же играет роль сам бизнес процесс, который и диктует требования к реализации.
51-
Всегда из поставленной задачи необходимо попытаться предположить как может измениться процесс. Так как можно усложнить приложение там, где никогда процесс работы не поменяется.
50+
The goal of OOP is to achieve polymorphism, which provides scalability of the project. Another advantage of OOP is encapsulation.
5251

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.
5553

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

Comments
 (0)