DEV Community

Cover image for WHY YOU SHOULD BE FOLLOWING THE SINGLE RESPONSIBILITY PRINCIPLE
Huzaifa Rasheed
Huzaifa Rasheed

Posted on • Edited on

WHY YOU SHOULD BE FOLLOWING THE SINGLE RESPONSIBILITY PRINCIPLE

For those of you already familiar with the SOLID Design Principles, this won't be much of a new thing. For newbies however

SOLID are 5 software development principles or guidelines based on Object-Oriented design making it easier for you to make your projects scalable and maintainable.

They are more like best practices rather than a rule.

SINGLE RESPONSIBILITY

The S in SOLID.

It says

A class should have one, and only one reason to change.

The goal is to separate behaviors or concerns. Everything has its own place and it should be placed there.

Basically

  1. Make smaller code modules (class/function etc)
  2. Module does a specific thing only and is liable for that only.
  3. It is named precisely for what it does.

As opposed to Large Generic classes with different responsibilities and behaviors.

This pattern can be seen in other SOLID principles like Interface Segregation where we focus on making role-specific interfaces.

A SIMPLE USE CASE

Let's say we are saving a random user's data to some database. This is what we would normally do inside a function(pseudocode-ish).

function createUser(userData){
    // 1. validate user data for email and password keys

    // 2. check if the email is already registered

    // 3. save the user to DB 

    // 4. return saved user as a response
}
Enter fullscreen mode Exit fullscreen mode

With the SINGLE RESPONSIBILITY approach we will make dedicated functions that would handle specific logic and be responsible for it only

function validateUser(user){
    // will validate userObject for email and password keys
}

function isEmailRegistered(email){
    // will check if the email is already taken 
}

function saveUserData(user){
    // will save user data to db
}

function createUser(userData){
    validateUser(userData)

    if(isEmailTaken(userData.email)){
      // throw some error here
    }

    var user = saveUserData(userData)

    return user
}
Enter fullscreen mode Exit fullscreen mode

This is a simple example but when dealing with multiple validations and complex logic this type of approach is really handy.

WHY USE IT

Consider these

  1. Easy to follow and Understand
  2. Debugging made easy
  3. Removing and refactoring is much simpler than before.
  4. You can make bigger changes without fear.
  5. It is scalable and maintainable

Also when there is a time you need-to/have-to/want-to/are-forced-to make changes and have followed SINGLE RESPONSIBILITY, then it will be much quick and easy.

What if you break something or there is a bug? Well, it is Easily traceable following this principle and if you break something, you break that one thing only, not an entire system.

Not to mention that this rule helps a lot in the implementation of other SOLID principles like Dependency Inversion and the Liskov Substitution Principle.

Tip

If you are someone that writes tests for their project then you would surely love this rule, it gives you predictable behavior and control.


Here it is guys, I hope I explained it in a simple and easy way. Do you use SOLID principles in your projects? Be sure to comment below.

What's Next

Laern about Open/Close Principle Principle in 2 Minutes.

Top comments (9)

Collapse
 
darkain profile image
Vincent Milum Jr

Now, one reason NOT to use SOLID. It looks good from the outside 99% of the time. But take another look at your example code. You've now introduced a race condition in your code between checking if an email address is already used, and then saving the new user data.

As someone that has done enterprise software engineering for ~15 years, these are now the sorts of things I look out for and have to engineer against. So when you see some more funky code, take a step back and ask "why is it done this way with this level of complexity?" - because more often then not, there are real world problems that need to be solved that cannot entirely be met with these ideals in mind.

Collapse
 
andreidascalu profile image
Andrei Dascalu

I don’t see a new race condition. The simple fact some code has been segregated to functions doesn’t introduce something new. That code won’t run in parallel by merely calling the methods in sequence so that one thing could get executed out of order and without waiting.

Collapse
 
darkain profile image
Vincent Milum Jr

It isn't because of separating them out into individual functions. It is that there could be multiple invocations at once, for instance two users attempting to register at the same time with competing information. And its because of situations like this why some code is written in a more complex way to handle these situations.

Thread Thread
 
zivce profile image
Milos Zivkovic

I guess if it is put in a step-wise class; where the order is obeyed. There shouldn't be a problem. We give this user flow exclusive access to these functions. Layout like this in the article would give headache if used inappropriately.

Thread Thread
 
andreidascalu profile image
Andrei Dascalu

Yeah, but that’s not because the code gets split in functions. The exact same thing applies to the original code.
That’s a whole different discussion beyond the point of illustrating a concept.

Collapse
 
rhuzaifa profile image
Huzaifa Rasheed • Edited

I appreciate your suggestion. I have a question and correct me if I am wrong, Does the Race Condition or Data Race also occur in single thread programs/code?

Collapse
 
darkain profile image
Vincent Milum Jr

If there is truly only one invocation possible at a time, then yes, that is fine. But that simply isn't scalable. If we're looking at a web application or API for instance, multiple users would be using the site at the same time.

Collapse
 
peerreynders profile image
peerreynders

It says

A class should have one, and only one reason to change.

The Single Responsibility Principle by Robert C. Martin (~2010):

Gather together those things that change for the same reason, and separate those things that change for different reasons.

YouTube

See also The Single Responsibility Principle (2014).

Collapse
 
carlosrafael22 profile image
Rafael Leitão

Great explanation, Huzaifa! Yeah, I always use it because it's also better to test :)