Header Ads Widget

Single Responsibility Principle in Javascript.

Single Responsibility Principle states that a function should be responsible for single peice of work. A single piece of work is easier to explain, understand and implement. Purpose behind this is to be specific rather than being generic.

Why Single responsibility Principle?

Look at the image above, it is a car. Its main purpose is to commute from one place to another but it is built with lots of components. Each component has its own work. If its tire is punctured, you can easily replace it or fix it. When a tire is punctured we have to fix the tire, not anything else. If its headlamp's bulb is fused we need to fix the buld not anything else. By seeing this example it is clear that when we design a complex system we break it down into different components. Each component has its own responsibility. And if we need to fix or enhance any of the components we fix that without touching other components.

Similar to the car when we design software, we have to combine different modules. Each module in software has to be responsible for a single task.

For Example, let's develop an AccountManager module. This module will only be responsible for money withdrawal and deposit. However, we know that when withdraw or deposit money there is a lot that happens under the hood. Like: We get SMS or email notifications, we get alerts for any error.

Below is an example of Single responsibility.

The above example is a very good demonstration of the single responsibility principle. We could have written logger and notifyUser module within the AccountManager module itself. Anyways these 2 modules are just doing alert() and console.log(). But We know that if there is any change to these modules we have to do the changes inside AccountManager which will be a bad way of designing software. That's why I created 2 different modules for these 2 tasks. Now, whenever there is any change in these modules we would directly go there and do the changes.
For example: if we have to change the date format of log message then we can do it in logger module.

Conclusion:

Like the real world, software is also made up of lots of components and we call it modules. It will be easier to maintain and enhance the software if we have segregated the responsibility. The single Responsibility Principle is one of the principles of SOLID Principle in oops design system.
Deciding what not to do is as important as deciding what to do. While writing code we have to make sure that we write clean and clear code which is very easy to explain and understand.

Post a Comment

0 Comments