Связность, связанность и разделение ответственности
Освойте три базовых свойства проектирования программного обеспечения, определяющих поддерживаемость кода: высокую связность, слабую связанность и чёткое разделение ответственности
«Связность, связанность и разделение ответственности» — бесплатный урок Clean Architecture & Design Patterns in Practice на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Clean Architecture & Design Patterns in Practice, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Clean Architecture & Design Patterns in Practice содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why These Properties Matter
Under clean code and SOLID lie three deeper design properties: cohesion, coupling, and separation of concerns. They explain why the rules work.
What is Cohesion
Cohesion measures how well a module’s responsibilities belong together. High cohesion = one well-defined job; low cohesion = a grab-bag of unrelated methods.
Low vs High Cohesion
Compare the two: the Util class mixes unrelated concerns, while UserRepository is tightly focused. That focus is high cohesion.
// Low cohesion
class Util {
saveUser() {}
sendEmail() {}
formatDate() {}
}
// High cohesion
class UserRepository {
save() {}
findById() {}
}What is Coupling
Coupling measures how much one module depends on another’s internals. Tight coupling spreads changes everywhere; loose coupling keeps interactions minimal.
Tight Coupling Example
Here OrderService creates its own SmtpMailer, locking it to that exact class. Swapping the mailer means editing the service — tight coupling.
class OrderService {
constructor() {
this.mailer = new SmtpMailer();
}
}Loosening the Coupling
Inject the mailer instead. Now OrderService depends on an abstraction and accepts any implementation. That’s loose coupling.
class OrderService {
constructor(mailer) {
this.mailer = mailer;
}
}The Sweet Spot
The sweet spot is high cohesion and low coupling together: focused modules that stay independent, so systems are easy to change, test, and reason about.
Separation of Concerns
Separation of concerns means splitting a program so each part owns one distinct concern — keep UI, business logic, and data access in separate layers.
Mixed Concerns
This function tangles data access, logic, and presentation together. Touch any one concern and you risk breaking the others — mixed concerns.
function showTotal(id) {
const rows = db.query('SELECT * FROM orders WHERE id=' + id);
const total = rows.reduce((s, r) => s + r.price, 0);
document.body.innerHTML = 'Total: ' + total;
}Separated Concerns
Split it into a repository, a calculator, and a view. Each concern now changes and tests independently. Much cleaner.
const order = repository.findById(id);
const total = calculator.total(order);
view.render(total);How They Connect to SOLID
These properties underpin SOLID: single responsibility drives cohesion, dependency inversion drives low coupling, and layering expresses separation of concerns.
Quick Check
High cohesion, low coupling — can you tell them apart?
Recap
You’ve got the foundations: cohesion keeps related work together, low coupling minimizes dependencies, and separation of concerns divides by purpose.
Часто задаваемые вопросы
Урок «Связность, связанность и разделение ответственности» бесплатный?
Да — полный текст урока «Связность, связанность и разделение ответственности» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Clean Architecture & Design Patterns in Practice, подпишись на CoddyKit PRO. Курс Clean Architecture & Design Patterns in Practice содержит 4 уроков всего.
Чему я научусь в уроке «Связность, связанность и разделение ответственности»?
Освойте три базовых свойства проектирования программного обеспечения, определяющих поддерживаемость кода: высокую связность, слабую связанность и чёткое разделение ответственности Ты практикуешь Clean Architecture & Design Patterns in Practice с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Clean Architecture & Design Patterns in Practice?
Предыдущий опыт не требуется. Clean Architecture & Design Patterns in Practice на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Связность, связанность и разделение ответственности»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Clean Architecture & Design Patterns in Practice?
Да. Каждый урок Clean Architecture & Design Patterns in Practice включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Введение в чистый код
- Обзор принципов SOLID
- Ценность хорошего проектирования
- Связность, связанность и разделение ответственности