0Pricing
Clean Architecture & Design Patterns in Practice · Lección

Dominio de la responsabilidad única y abierto-cerrado

Profundice en el dominio de los dos primeros principios SOLID y aprenda a identificar los límites de responsabilidad y a ampliar el comportamiento sin modificar el código existente.

Dominio de la responsabilidad única y abierto-cerrado es una lección gratuita de Clean Architecture & Design Patterns in Practice en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Clean Architecture & Design Patterns in Practice, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Clean Architecture & Design Patterns in Practice incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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.

Preguntas frecuentes

¿La lección «Dominio de la responsabilidad única y abierto-cerrado» es gratis?

Sí — el texto completo de «Dominio de la responsabilidad única y abierto-cerrado» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Clean Architecture & Design Patterns in Practice, actualiza a CoddyKit PRO. El curso de Clean Architecture & Design Patterns in Practice incluye 4 lecciones en total.

¿Qué aprenderé en «Dominio de la responsabilidad única y abierto-cerrado»?

Profundice en el dominio de los dos primeros principios SOLID y aprenda a identificar los límites de responsabilidad y a ampliar el comportamiento sin modificar el código existente. Practicas Clean Architecture & Design Patterns in Practice con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Clean Architecture & Design Patterns in Practice?

No se requiere experiencia previa. Clean Architecture & Design Patterns in Practice en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Dominio de la responsabilidad única y abierto-cerrado»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Clean Architecture & Design Patterns in Practice?

Sí. Cada lección de Clean Architecture & Design Patterns in Practice incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Profundización en la inversión de dependencias
  2. Segregación de interfaces en la práctica
  3. Refactorización con patrones de diseño
  4. Dominio de la responsabilidad única y abierto-cerrado
← Volver a Clean Architecture & Design Patterns in Practice