Agile Software Development# 8.SRP: The Single-Responsibility Principle

8.SRP: The Single-Responsibility Principle

 

A classs should have only one reason to change.

 

📌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

image-20220202110953677

 

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.

image-20220202112303117

 

📌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:

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

image-20220202114505520

 

⭐In a nutshell, what and when should we do this?

An axis of change is an axis of change only if the changes actually occur.

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.

image-20220202120149026

The Employee class contains business rules and persistence control. When facing with similar problems, try to use FACADE and PROXY design pattern.

Previous
Previous

Agile Software Development# 9.OCP: The Open-Closed Principle

Next
Next

Agile Software Development# 07 What is Agile Design?