paint-brush
SOLID: Learn About the Single Responsibility Principle With Examplesby@ggorantala
22,420 reads
22,420 reads

SOLID: Learn About the Single Responsibility Principle With Examples

by Gopi GorantalaAugust 18th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In conclusion, the Single Responsibility Principle (SRP) is a software design principle that states that every class should have only one reason to change.
featured image - SOLID: Learn About the Single Responsibility Principle With Examples
Gopi Gorantala HackerNoon profile picture

In this article, you will learn about the following:


  1. What is SRP?
  2. Importance of SRP in software development
  3. Strengths
  4. Weaknesses
  5. Twitter Registration

What Is SRP?

The Single Responsibility Principle (SRP) is one of the five SOLID design principles that guide software development.


Definition: A class or module should have only one reason to change.


The principle states that a class should have only one reason to change and one responsibility. This principle is intended to promote modularity and help developers create easier code to understand, modify, and maintain.


In essence, the SRP states that each class should have a single, well-defined responsibility and that responsibility should be encapsulated within that class.


This means that a class should not have multiple responsibilities, as this can make it harder to understand and modify. By following the SRP, developers can create more maintainable and flexible code that is easier to work with over time.


The SRP is a fundamental principle in object-oriented programming, and it can significantly impact the quality and effectiveness of software development. We will explore the SRP in more detail, including how it works, why it is important, and how to apply it effectively in Java programming.

Importance of SRP in Software Development

There are several reasons why SRP is important in software development:

  1. Enhances code readability: Reading and understanding the code becomes easier when each class or module has a single responsibility. This helps developers quickly understand the purpose of the class or module and its relationship with other parts of the system.


  2. Increases code maintainability: By breaking down complex functionality into smaller, more focused modules, SRP enables developers to make changes to the code more easily without affecting other parts of the system. This means that maintenance and troubleshooting of the code become less time-consuming and costly.


  3. Facilitates code reuse: Code that adheres to SRP is often more modular and reusable. This means developers can easily reuse the code in other parts of the system or projects.


  4. Improves system scalability: Maintaining a single responsibility for each class or module becomes increasingly important as the codebase grows. SRP ensures that the codebase remains scalable and can easily accommodate changes or new features without impacting the rest of the system.


Overall, adhering to the Single Responsibility Principle improves the quality and maintainability of the codebase, making it easier to manage, test, and deploy.

Advantages

The advantages of following the Single Responsibility Principle (SRP) include the following:


  • Better code organization and maintainability.


  • Improved readability and understanding of code.


  • Easier debugging and testing of code.


  • A higher degree of code reusability.


  • Facilitation of parallel development and implementation of new features.


  • Ability to make changes to code with less risk of introducing bugs.

Disadvantages

Some of the disadvantages of the Single Responsibility Principle (SRP) include the following:


  • Increased complexity, as a system may require more classes to implement the same functionality.


  • Potential for over-engineering, leading to too much abstraction and unnecessary code.


  • Difficulties in determining the appropriate granularity of responsibilities.


  • Challenges in balancing the trade-off between separating responsibilities and maintaining performance.


When programmers try to add features or new behavior to a software product, they frequently integrate everything within the current class. When something needs to be changed later, due to the complexity of the code, the code refactor process is extremely time-consuming and tedious.


The Single Responsibility Principle helps us create simple classes that perform just one task. This helps make modifications or adding extensions to the existing code much more effortless.

Twitter Registration Using Single Responsibility Principle

We design Twitter registration software with the help of the single responsibility principle that contains a notification service, database repository, account service, and execution class.


Let's implement the first design principle on Twitter registration flow.

🔐 Signup Process on Twitter

Consider a use case where a user wants to register with Twitter. The steps Twitter takes to register are user are:


  1. Twitter asks users to register with signup forms.


  2. Twitter stores the user object in its database, which contains User details - emailnamepassword, and other metadata, etc.


  3. Twitter sends a welcome message to the user.


Let us declare a class that does the above steps.


public class TwitterRegistration {
    public void register() {
        // step 1
        System.out.println("Fill signup form");

        // step 2
        System.out.println("Store account details in database");

        // step 3
        System.out.println("Send a welcome message");
    }
}


We are creating an account on Twitter, and the three steps should be handled separately. But the above class declared them all in a single TwitterRegistration class. Isn't this a violation of SRP?


Also, step 2 of storing an object in the database requires additional work to open a connection with the database, authenticate the handshake, and store the user object. This is insertion logic and should be handled separately.


The third step is sending out a welcome message to the user, which should be handled by NotificationService, separately.


Using the SRP principle, we divide the above TwitterRegistration class into three different classes, each having a single and only one responsibility.

Refactoring for SRP

Refactoring TwitterRegistration the class gives:

// Notification Service
class NotificationService {
    public void sendNotification() {
        // step 3
        System.out.println("Send out welcome message");
    }
}


// Database handshakes
class AccountRepository {
    public void createUser() {
        // step 2
        System.out.println("🔐 Auth Success!");
        System.out.println("Store user data into database");
    }
}


// Account Registration
class TwitterAccountRegister {
    public void registerUser() {
        // step 1
        System.out.println("fill account internal details");
    }
}


Finally, after refactoring the above classes. We first allow the TwitterAccountService to create a couple of objects for AccountRepository and NotificationService to register users with Twitter.


// Execution Class or Main class
public class TwitterAccountRegister {
    public static void main(String[] args) {
        TwitterAccountService service = new TwitterAccountService();
        service.registerUser();
    }
}

// Account Registration Service
class TwitterAccountService {
    AccountRepository repository = new AccountRepository();
    NotificationService notificationService = new NotificationService();

    public void registerUser() {
        // step 1
        System.out.println("fill account internal details");

        repository.createUser();
        notificationService.sendNotification();
    }
}

// Notification Service
class NotificationService {
    public void sendNotification() {
        // step 3
        System.out.println("Send out welcome message");
    }
}

// Database handshakes
class AccountRepository {
    public void createUser() {
        // step 2
        System.out.println("🔐Signup Success!! Registered");
        System.out.println("Store user data into database");
    }
}

/*
Outputs:
fill account internal details
🔐Signup Success!! Registered
Store user data into database
Send out welcome message
*/


In above, TwitterAccountService is doing all three tasks. The primary responsibility is to fill in account details in account details and delegate the other responsibilities to other classes.


Finally, we know many teams work on the same software product.


By following the SRP principle, if we see file changes in GitHub for a file named TweetAnalytics, we can be sure that the changes incorporated are related to analytics. This helps version control with ease.

Conclusion

In conclusion, the Single Responsibility Principle (SRP) is a software design principle that states that every class should have only one reason to change.


Following SRP makes code easier to understand, maintain, and extend. It reduces the risk of introducing bugs and makes it easier to test individual components in isolation.


SRP encourages the separation of concerns, making the code more modular and scalable. This principle is one of the five SOLID principles of object-oriented design and is an important aspect of creating clean, maintainable, and scalable code.


You will get the complete written notes @ <https://www.ggorantala.dev/ ](https://www.ggorantala.dev/)


Also published here