Design Pattern - Single Responsiblity Principle

Single Responsibility Principle (SRP) states that a class should have only one reason to change. This means that a class should have only one responsibility, and that it should be focused on doing one thing well. The idea behind this principle is that by keeping classes focused and cohesive, we can make our code more maintainable and easier to understand.

Example in C#

class OrderProcessor {
    public void ProcessOrder(Order order) {
        // validate the order
        ValidateOrder(order);
        
        // save the order details
        SaveOrder(order);
        
        // send an email to the customer
        SendEmail(order.Customer);
        
        // print a copy of the order
        PrintOrder(order);
    }
}

In the above example, the OrderProcessor class is responsible for handling several different responsibilities including validating the order, saving the order to the database, sending an email to the customer, and printing a copy of the order.

Lets refactor the above code to follow the SRP

class OrderValidator {
    public void ValidateOrder(Order order) {
        // validate the order
    }
}


class OrderSaver {
    public void SaveOrder(Order order) {
        // save the order details
    }
}


class CustomerNotifier {
    public void SendEmail(Customer customer) {
        // send an email to the customer
    }
}


class OrderPrinter {
    public void PrintOrder(Order order) {
        // print a copy of the order
    }
}

In this refactored version, each responsibility has been extracted into its own class. The OrderValidator class is responsible for validating orders, the OrderSaver class is responsible for saving orders to the database, the CustomerNotifier class is responsible for sending emails to customers, and the OrderPrinter class is responsible for printing copies of orders. This separation of responsibilities makes the code more maintainable and easier to understand.


Most Read