Ronaldo Vitto Lewerissa

Software engineering learning documentation.

Single Responsibility Principle

This is a brand new concept I just learnt. Having this concept in mind will generally make us able to design a more robust software architecture.

Single Responsibility Principle is deeply related to Coupling and Cohesion, which also relates to the idea of separating concerns (The separation of Concerns).

Uncle Bob states that SRP is the idea in which:

Each software modules should have one and only one reason to change.

Well, I did not grasp it instantly the first time I hear about it. Reason to change? What the heck it's suppose to mean?

Turns out it's not that complicated though. Theoretically.

Single Responsibility Principle is all about people.

Who do you think will likely to care about the method you wrote on class Foo?

Who do you think will likely to request changes on the method you wrote on class Bar?

If more than a single person or -- as stated by Uncle Bob -- a single tightly coupled group of people representing a single narrowly defined business function, it is likely that you violate Single Responsibility Principle!

For instance (example from here):

public class Employee {  
  public Money calculatePay();
  public void save();
  public String reportHours();

The financial department will likely to care about calculatePay() method.

The IT department will likely to care about save() method.

The operational department will likely to care about reportHours() method.

If, for instance, financial department request changes on calculatePay() and accidentally breaks reportHours(), whose fault is this!?

If each methods otherwise be separated to it's own class, this sort of accident would not have happened!

Written by Ronaldo Vitto Lewerissa

Read more posts by this author.