Single Responsibility Principle (SRP)

Single Responsibility Principle (SRP)

S.O.L.I.D principles series

A class should only have one reason to change, or one responsibility, in accordance with the Single Responsibility Principle (SRP). This idea makes the code easier to comprehend and maintain by promoting a clear division of responsibilities.

One way to achieving the SRP is to divide various responsibilities into separate classes. By encapsulating a certain behaviour, this makes each class more cohesive and comprehensible.

For example, consider a class named "Musician" which is responsible for sing, play the guitar and play drums:

This violates the SRP because it has 3 distinct responsibilities: sing, play the guitar and play drums. Instead, we can create separate classes for each responsibility, such as a Singer class, Guitarist class and a Drummer class:

With the previous diagram, the responsibilities of sing, play the guitar and dance are separated into their own classes, following the SRP:

  • A guitarist is responsible for playing the guitar chords

  • The singer is responsible for sing the lyrics

  • And the drummer provide rhythm and beat to a performance

Similarly, in programming, classes should have clear and distinct responsibilities to avoid overlap and confusion. Let's see an implementation example:

class Singer {
  public sing() {
    console.log("Singing the lyrics");
  }
}

class Guitarist {
  public play() {
    console.log("Playing the guitar");
  }
}

class Drummer {
  public play() {
    console.log("Playing the drums");
  }
}

// Creating instances of each musician
const singer = new Singer();
const guitarist = new Guitarist();
const drummer = new Drummer();

singer.sing();
guitarist.play();
drummer.play();

Single Responsibility Principle doesn’t mean do only one job, it means that everything it does should be closely related

See you in the next article of this series.

Did you find this article valuable?

Support Señor Developer by becoming a sponsor. Any amount is appreciated!