SOLID: Single Responsibility Principle

Get familiar with the single responsibility principle along with its examples.

Introduction

The Single Responsibility Principle (SRP) is perhaps the least understood of the SOLID concepts. The term was coined by Robert C. Martin who defines the SRP in the following way, "A class should have only one reason to change." This implies that any class or component in our code should only have one functionality. Everything in the class should be related to just one goal.

When programmers need to add features or new behavior, they frequently integrate everything within the current class. When something needs to be changed later, due to the complexity of the code, the update process becomes extremely time consuming and tedious. The Single Responsibility Principle helps us create simple classes that perform just one task. This helps in making modifications or adding extensions to the existing code much easier.

Real-life example

The following illustration represents how SRP is applied in real life:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.