Single Responsibility Principle

March 26, 2021

Single Responsibility Principle

You may have heard the term "single responsibility principle" before, but what does it mean?

The single responsibility principle dictates that your classes should have only one responsibility. Not two. Just one. If you follow this principle, you can reduce tight coupling and make your code easier to refactor.

It can be tempting to keep adding methods to an existing class, especially when working with an older codes. Resist it. Whenever you're about to add a method to a class, ask, "does this method I am about to add fall within the scope of this class?".

If yes, add to it. If no, put it in a different / new class.

For example, if you are writing a password validator logic for the CreateUser class, you're thinking of adding it in that class. Take a step back and ask, "does the responsibility of validating a password fall under the CreateUser class?".

In this case, the answer is no. CreateUser's responsibility is to handle user creation. It makes more sense to create a new class, Validate, to handle password validation. In the future you can reuse it to not only handle password validation, but other validations like username, email, product description, etc. By creating a new Validate class, you create a space to put all future validation logics in.

The single responsibility principle can be applied not only in classes, but also to modules, services, applications, and even systems.