SRP: The single responsibility principle explained clearly

The single responsibility principle (SRP) is a computer programming principle that states that a module, a function, or a class should be responsible for only one action.

What is the single responsibility principle?

As explained in the introduction, The single responsibility principle (SRP) is a computer programming principle that states that a module, a function, or a class should be responsible for only one action. The term was introduced by Robert C. Martin, a famous American software engineer, in one of his articles about Object Oriented Design (OOD).

What are its benefits?

SRP makes the code more compact and packaged into functions, helping to make it more reusable and avoid wasting time re-coding what has already been done. The use of SRP helps by reducing points of concern to improve code updating efficiency. SRP also reduces object length, one of the bases of writing clean code

Some practical examples

This concept is very complicated. To understand it easier i’ve made some practical examples.

def monthly_balance() :
   calculate_revenue()
      #code
   calculate_spendings()
      #code
   calculate_monthly_balance()
      #code
   display_monthly_balance()
      #code
   send_monthly_balance_notification()
       #code

The function “monthly_balance” contains 5 subfunctions. Even though this code is well organised, it doesn’t satisfy SRP requests, because the general class has got a lot of “responsibilities”.

def calculate_revenue()
   #code
 def calculate_spendings()
   #code
 def calculate_monthly_balance()
   #code
def display_monthly_balance()
   #code
def send_monthly_balance_notification()
   #code

In this code is applied the SRP. Every function has only 1 responsibility and performs only an action. Non this code is easier to understand, modify and maintain. That’s it!

Conclusion – Single responsibility principle

In this article, we discovered what is Single responsibility principle, who invented it, its benefits, and how to apply it to your code with practical examples.

Now it’s your turn.

Will you start using SRP in your codes to improve your working efficiency and productivity?

If you liked this article consider subscribing to my newsletter to keep informed about the fastest-developing and most important industry in the world.

Share the knowledge

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *