SOLID Principles

 SOLID Principles

S - Single Responsibility Principle

A class is responsible only for a single task

Suppose we need to process a order where set of task need to be done like validate order, save order and send notification to the customer.

Bad Practice:

public class OrderProcessor {     //define the subtask to process order     public void ValidateOrder() { //definition goes here}     public void SaveOrder() { //definition goes here}     public void SendNotification() {//definition goes here}

    public void Process()     {         ValidateOrder();         SaveOrder();         SendNotification();     } }

The above example violates the single responsibility principle. Because a single class take all the responsibility to process order.

Good Practice:

public class OrderProcessor {     private readonly OrderValidator orderValidator;
    private readonly OrderSaver orderSaver;
    private readonly OrderNotificationSender orderNotificationSender;

    public OrderProcessor(OrderValidator orderValidator, OrderSaver orderSaver,   OrderNotificationSender orderNotificationSender)
{
this.orderValidator = orderValidator;
this.orderSaver = orderSaver;
this.orderNotificationSender = orderNotificationSender;
}

    public void Process()
    {
            orderValidator.Validate();
            orderSaver.Save();
            orderNotificationSender.SendNotification();
    }
}

public class OrderValidator
{
Public Void Validate() { //definition goes here }
}

public class OrderSaver
{
Public Void Save() {
//definition goes here } }

public class OrderNotificationSender
{
Public Void SendNotification() {
//definition goes here } }



O - Open Closed Principle
Open for extension but closed for modification

Suppose we have a new requirement like need to save the order info into cache along with database.

Bad Practice:

public class OrderSaver {     public void Save() { //definition goes here}

    public void SaveCache() { //definition goes here} }

Here we modify the existing class which violates the open close principle.

Good Practice:

public interface iOrderSaver {     public void Save(Order odrObj); }

public class DatabaseSaver : iOrderSaver {     public void Save(Order odrObj) { //definition goes here } }

public class CacheSaver : iOrderSaver {     public void Save(Order odrObj) { //definition goes here } }


L - Liskov Substitution Principle
A subclass should be substitutable by a base class without having any negative impact to the caller

I - Interface Segregation Principle
Multiple specific interfaces are better than generic single interface

D - Dependency Inversion Principle
Classes should only depend on contracts, meaning interfaces or abstract classes rather than concrete implementation.

Comments