Single Responsibility Principle

Prashant Jha
3 min readMar 20, 2023

--

While we can write code, it is very crucial to write clean code. And to write better code we can follow SOLID design principles. That will help us to write more maintainable and scalable code. Where features can be added very efficiently and easily without breaking the existing code. So that we can spend more time on writing the code instead of understanding it. I’ll be writing blogs on each principle of SOLID to give a concrete understanding and a better explanation. Feel free to follow along starting with S i.e., Single Responsibility principle.

Single responsibility principle says a component should have one and only one reason to change. That means a component should be doing only one kind of work. If there are 2 or more different functionalities then those functionalities should reside in another components even if those are small ones. So that later on scaling those small components will be easy enough and we can add more features to that component without effecting the other functionality in parent component.

Here as we can see, in this Gym component we are writing 2 entirely different functions in terms of working. One is to calculate gym hour and the other is to notify the ‘gym rat’ as soon as gym hour is exceeding the maximum gym hours allowed. Now, if we will update any of those 2 functions we are updating parent component. Which is violating the single responsibility principle. Which says that there must be only one reason to change the component.

For separation of concern and according to single responsibility principle we should write one function in another component so that scaling that code will be easier in future. By looking at functionality of this program we can see that it’s better to separate notification function into another component because there is more probability of scaling of that component like in future we may want to send a notification email also or a WhatsApp message to notify that ‘gym rat’.

So it’s better to write code like :-

Here we wrote another component for notification

and lazy loaded/imported that component in main Gym component.

Here we can clearly see the separation of concern and scaling that Notification component will be much more easy and reliable in future without effecting the main parent component.

This concludes single responsibility principle, ‘S’ in ‘SOLID’ principles. Feedback is always appreciated. If you like this article please give a clap and comment your suggestions also. Thank You!!

--

--

Prashant Jha
Prashant Jha

Written by Prashant Jha

interested in Code, Books, Philosophy, Poems

No responses yet