You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
6 Hrs
14 Min
49 Seg

Conociendo el principio de responsabilidad única

5/16
Resources

What is the single responsibility principle in SOLID?

The SOLID framework is fundamental to object-oriented programming and one of its cornerstones is the Single Responsibility Principle. This principle, known as the Single Responsibility Principle (SRP), states that each component within a system must have a single responsibility. This rule is crucial to ensure code cohesion and modularity, offering advantages such as increased maintainability and ease of testing.

How is this principle applied in C#?

When you implement the single responsibility principle in C# or any other language that supports object-oriented programming, each class or method must perform a specific task.

  • Classes: A class must be bound to a single model and limited to a specific system responsibility.
  • Methods: Each method must perform a single operation; their names must clearly reflect the action or task they perform.

System components under SRP?

The single responsibility principle applies not only to methods and classes, but extends to other system components:

  • Modules: Each module must concentrate on performing a single function.
  • Libraries: They must contain specific functionalities, without mixing them with other responsibilities.
  • Microservices: In modern architectures, each microservice should handle a single responsibility or process.

Practical example: Analysis of a user story

Let's analyze the following requirement: as a user, after confirming a purchase, I expect to receive a confirmation message, to be able to download an invoice and to receive a confirmation email. At first glance, this user demands three simultaneous actions, which, from a programming point of view, does not imply that we should create a single class or method that covers all these functions.

  • Purchase confirmation: Display a confirmation message and save the event in the database.
  • Invoice download: Facilitate the download of the payment receipt.
  • Confirmation email: Send an email as proof of the completed process.

Instead of creating a monolithic solution, we should separate these actions into different components or services, each with its own defined responsibility.

Case Study: Student Repository

In the course we will analyze a demo with a class called StudentRepository. This class does not currently comply with the single responsibility principle. This will be a practical exercise to identify its deficiencies and refactor the code to comply with the SRP, ensuring that each part of the system maintains a single specific task.

In conclusion, effective use of the Single Responsibility Principle not only improves code structure and maintainability, but also paves the way for future extensions, making them less error prone and easier to update. Keep learning and improving your programming skills!

Contributions 7

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Básicamente “divide y vencerás”

## Principio de Responsabilidad Única (SRP) en C\# **Definición:** El **principio de responsabilidad única (SRP)** establece que cada clase o módulo en un programa debe tener una única responsabilidad. En otras palabras, una clase solo debe tener una razón para cambiar. **Beneficios:** * **Mejora la modularidad:** Permite dividir el código en unidades más pequeñas y cohesivas. * **Facilita el mantenimiento:** Hace que el código sea más fácil de entender y modificar. * **Reduce la acoplamiento:** Limita la dependencia entre diferentes partes del código. * **Mejora la testabilidad:** Permite escribir pruebas unitarias más precisas. **Cómo aplicar el SRP en C#:** * **Identificar las responsabilidades:** Divide la funcionalidad del programa en responsabilidades discretas. * **Agrupar las responsabilidades:** Agrupa las responsabilidades relacionadas en clases o módulos. * **Utilizar interfaces:** Define interfaces para abstraer las responsabilidades. * **Evitar la dependencia mutua:** Minimiza la dependencia entre diferentes clases o módulos. **Ejemplos de aplicación del SRP:** * **Clase** `Persona`**:** Tiene la responsabilidad de almacenar información personal (nombre, dirección, etc.). * **Clase** `Calculadora`**:** Tiene la responsabilidad de realizar operaciones matemáticas (suma, resta, etc.). * **Clase** `Repositorio`**:** Tiene la responsabilidad de acceder y modificar datos en una base de datos. **Violaciones del SRP:** * **Clases con múltiples responsabilidades:** Una clase que gestiona la interfaz de usuario y la lógica de negocio. * **Clases con responsabilidades no relacionadas:** Una clase que calcula impuestos y también envía correos electrónicos.

Con este principio todo se hace más fácil, el manejo y la gestión

Single responsability principle
Se trata de distribuir las responsabilidades de un software en un grupo de componentes, haciendo que cada componente tenga una única responsabilidad. Aplica para:

  • Módulos
  • Clases
  • Métodos
  • Funciones

Pincipio de responsabilidad unica
Distribuir las responsabilidades de un sistema entre sus componentes, donde cada uno solo tengo una responsabilidad.

Pudiera parecer que a la larga pudiéramos llenarnos de muchos archivos o componentes, pero en la experiencia que tengo, es mucho mejor tener dividido y apoyado de un buen naming, será muy sencillo administrarlo.

Buen curso