0Pricing
Clean Architecture & Design Patterns in Practice · Урок

Мастерство принципов единственной ответственности и открытости/закрытости

Углубите понимание первых двух принципов SOLID: научитесь определять границы ответственности и расширять поведение, не изменяя существующий код.

«Мастерство принципов единственной ответственности и открытости/закрытости» — бесплатный урок 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 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Back to the Foundations

You have explored Dependency Inversion and Interface Segregation. This lesson masters the remaining pair:

  • Single Responsibility Principle (SRP)
  • Open-Closed Principle (OCP)

These two drive most everyday refactoring decisions.

SRP Defined Precisely

SRP says a class should have one reason to change. A reason to change maps to a single actor or stakeholder.

If billing rules and report formatting can change independently, they belong in different classes.

Spotting an SRP Violation

This class mixes calculation, persistence, and presentation.

class Employee {
    double calculatePay() { return 0; }
    void save() { /* DB code */ }
    String reportHtml() { return "<html>"; }
}

Refactoring Toward SRP

Split responsibilities so each changes for one reason.

class PayCalculator { double calculate(Employee e) { return 0; } }
class EmployeeRepository { void save(Employee e) {} }
class EmployeeReporter { String html(Employee e) { return "<html>"; } }

The Cohesion Payoff

After the split, each class is more cohesive: everything inside relates to one job.

Changes are localized, tests are focused, and accidental coupling between unrelated concerns disappears.

OCP Defined

The Open-Closed Principle: software entities should be open for extension but closed for modification.

You should be able to add new behavior by writing new code, not editing existing, tested code.

An OCP Violation

Adding a shape forces editing this method every time.

double area(Shape s) {
    if (s.type.equals("circle")) return 3.14 * s.r * s.r;
    else if (s.type.equals("square")) return s.side * s.side;
    return 0;
}

Closing It With Polymorphism

Make each shape compute its own area. New shapes require no edits to existing code.

interface Shape { double area(); }
class Circle implements Shape {
    double r;
    public double area() { return 3.14 * r * r; }
}
class Square implements Shape {
    double side;
    public double area() { return side * side; }
}

OCP Through Strategy and Plugins

Common OCP-enabling techniques:

  • Polymorphism over conditionals.
  • The Strategy pattern to inject varying behavior.
  • Plugin or registry mechanisms for adding handlers.

All let you extend by adding, not editing.

How SRP and OCP Reinforce Each Other

A class with a single responsibility is much easier to keep closed for modification, because there is only one axis of change.

When you cleanly separate responsibilities, extension points emerge naturally.

Pragmatic Limits

Do not over-apply. Premature abstraction for variation that never comes adds needless complexity.

Apply OCP at the points your domain actually varies; let the rest stay simple until change demands it.

Quick Check

Test your grasp of SRP and OCP.

Recap

You mastered the first two SOLID principles.

  • SRP: one reason to change per class.
  • OCP: extend by adding, not editing.
  • They reinforce each other and guide most refactorings, applied where variation truly exists.

Часто задаваемые вопросы

Урок «Мастерство принципов единственной ответственности и открытости/закрытости» бесплатный?

Да — полный текст урока «Мастерство принципов единственной ответственности и открытости/закрытости» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Clean Architecture & Design Patterns in Practice, подпишись на CoddyKit PRO. Курс Clean Architecture & Design Patterns in Practice содержит 4 уроков всего.

Чему я научусь в уроке «Мастерство принципов единственной ответственности и открытости/закрытости»?

Углубите понимание первых двух принципов SOLID: научитесь определять границы ответственности и расширять поведение, не изменяя существующий код. Ты практикуешь 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 — локальная установка не требуется.

Все уроки этого курса

  1. Подробно о принципе инверсии зависимостей
  2. Разделение интерфейсов на практике
  3. Рефакторинг с помощью паттернов проектирования
  4. Мастерство принципов единственной ответственности и открытости/закрытости
← Назад к Clean Architecture & Design Patterns in Practice