Uncategorized

S is for Single Responsibility Principle

Introduction

This is the first post in a five part series about object oriented design principles called SOLID.

In Sofware engineering, there is an acronym called SOLID which represents five design principles which intent is writing software that is easier to make and maintain.

SOLID stands for:

  • Single Responsibility Principle
  • Open-Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle

Single Responsibility Principle

Single Responsibility Principle is one of the easiest object oriented principles to understand, but in the practice, people tend to violate this principle. The abbreviation that is often used for this principle is SRP.

Single Responsibility Principle says that a class should have only one reason to change.

If class or module have more than one reason to change, then you violate this principle. Solution to that problem is to refactor your class to have only one responsibility.

Let’s take look at the class below. We have a class that has only one responsibility and that is to save an author. It is obvious that this class follows SRP principle.

public class AddAuthorsInteractorImpl implements AddAuthorsInteractor{
  
  private AuthorsRepository authorRepository;
  
  public AddAuthorsInteractorImpl(AuthorsRepository authorRepository) {
    this.authorRepository = authorRepository;
  }

  @Override
  public Author saveAuthor(Author author) {
    return authorRepository.save(author);
  }

}

 Conclusion

The Single Responsibility Principle is probably one of the easiest object oriented design principles to understand. The reality is different because it is not that easy to recognize where is a good place to apply this principle. People tend to overuse this principle or to create a god classes where they implement common stuff. So, it is really important to find balance and objectively take look at your code and implement this principle where it is needed.

No Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.