Domínio da Responsabilidade Única e do Aberto-Fechado
Aprofunde seu domínio dos dois primeiros princípios SOLID, aprendendo a identificar limites de responsabilidade e a ampliar comportamentos sem modificar código existente.
Domínio da Responsabilidade Única e do Aberto-Fechado é uma aula grátis de Clean Architecture & Design Patterns in Practice no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Clean Architecture & Design Patterns in Practice, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Clean Architecture & Design Patterns in Practice inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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.
Perguntas Frequentes
A aula “Domínio da Responsabilidade Única e do Aberto-Fechado” é grátis?
Sim — o texto completo de “Domínio da Responsabilidade Única e do Aberto-Fechado” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Clean Architecture & Design Patterns in Practice, atualize para CoddyKit PRO. O curso de Clean Architecture & Design Patterns in Practice inclui 4 aulas no total.
O que vou aprender em “Domínio da Responsabilidade Única e do Aberto-Fechado”?
Aprofunde seu domínio dos dois primeiros princípios SOLID, aprendendo a identificar limites de responsabilidade e a ampliar comportamentos sem modificar código existente. Você pratica Clean Architecture & Design Patterns in Practice com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Clean Architecture & Design Patterns in Practice?
Nenhuma experiência prévia é necessária. Clean Architecture & Design Patterns in Practice no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Domínio da Responsabilidade Única e do Aberto-Fechado”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Clean Architecture & Design Patterns in Practice?
Sim. Cada aula de Clean Architecture & Design Patterns in Practice inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Aprofundamento na Inversão de Dependência
- Segregação de Interfaces na Prática
- Refatoração com Padrões de Projeto
- Domínio da Responsabilidade Única e do Aberto-Fechado