Thursday 19 December 2019

SOLID Design Principles in C# - Single Responsibility Principle (SRP)


A class or module should have one, and only one, reason to be changed.

Usually a developer writes the code with their best knowledge, sometimes they end up building the class which will perform the multiple responsibilities.

Everything works fine in the initial step, but later if the requirement changes then class maintenance and testing will be difficult to manage.

Real Time Example:
For instance in start up company few can manage all the responsibilities of it. 
But if you consider in a big organization they have different departments managed by the skilled professional who are expertise in respective areas.So that everyone handles individual responsibilities rather than handling multiple, by this maintenance will be easier, deliverable, issue fixes, managing success rate leads to company growth.  

Class with multiple responsibilities


internal class EmployeeHandler
{
    internal string EmployeeName { get; set; }
    internal string Address { get; set; }

    internal void SaveEmployeeDetails()
    {
        // Code to save the details in Database
        // Connect to Database and open DB connection
        // Logical checks
        // Process DB oprations to DB
        // Close the connection
    }
}

The above class is violating the Single Responsibility Principle because of the following reasons.
    1. We have to changes the class if we need to add new attributes.
    2. If any database changes occurred we need to modify this class.
    3. Overtime the class size will expand and maintenance will be hard.

What's the solution?

Designing the classes with Single Responsibility


internal class EmployeeDetails
{
    internal string EmployeeName { get; set; }
    internal string Address { get; set; }
}

internal class PersistEmployee
{
    internal void SaveEmployeeDetails()
    {
        // Code to save the details in Database
        // Connect to Database and open DB connection
        // Logical checks
        // Process DB operations to DB
        // Close the connection
    }
}

Benefits of above classes:

1. The changes occurred in Employee Details class doesn't need to take care in another class. Like wise changes occurred in the class connected to database class doesn't need to take care in employee details class.  
2. The code is simpler, easy to maintain and understand.

Conclusion — Single responsibility is most considerable principle in code refactoring. This makes our code self explanatory, decouple the classes and easy to maintain.  

Please check my below posts on other SOLID principles for better understanding
Open/Closed Principle (OCP)


Interface Segregation Principle (ISP)

No comments: