Agile Software Development# 8.SRP: The Single-Responsibility Principle
8.SRP: The Single-Responsibility Principle
📌Why is IMPORTANT to separate responsibilities?
- 1️⃣If a class has more than 1 responsibility, then there will be more than 1 reason for it to change⚠.
- 2️⃣If a class has more than 1 responsibility, then the responsibilities become coupled⚠.
Therefore, the coupling leads to fragile designs that break in unexpected ways when changed.
📌Coupled Design - more than 1 responsibility
The Rectangle
above holds 2 responsibilities:
- 1️⃣ it provides a mathematical model of the geometry of a rectangle. (for Computational Geometry Application)
- 2️⃣ it renders the rectangle on a graphical user interface (for GUI)
📌Side Effect of Coupled Design
1️⃣ we must include the GUI in the computational geometry application => linked time, compile time,⚠ etc.
2️⃣ one change leads to another => rebuild, retest, redeploy,⚠ etc.
📌Decoupled Design
A better design is to separate the two responsibilities into two completely different classes as the following.
📌What is a Responsibility? When should be separated?
Answer to the 1st question: it depends.
Answer to the 2nd question: it also depends...
Considering the following interface
for a modem:
interface Modem
{
public void dial(String pno);
public void hangup();
public void send(char c);
public char recv();
}
You probably think the definition is quite enough: the responsibility of Modem
is the responsibility of Modem
But it can be sliced into the following:
Connection Management
dial
hangup
Data Communication
send
recv
⭐In a nutshell, what and when should we do this?
Sooner will cause Needless Complexity.
Later will cause Rigidity.
📌Compromised Separation
The ModemImplementation
class is still a class containing 2 responsibilities. 🙊 Sometime we are forced to couple things that we’d rather not couple... The compromised solution is to separate interfaces of decoupled concept.
📌Persistence
Binding business rules to the persistence subsystem is asking for trouble🙉. Because business rules tend to change frequently..
e.g.
The Employee class contains business rules and persistence control. When facing with similar problems, try to use FACADE and PROXY design pattern.