SOLID Principles

SOLID Principles by Robert C. Martin (with C# Examples & Simple Use Cases)

SOLID is a set of five design principles created by Robert C. Martin (Uncle Bob) to help developers write clean, maintainable, and scalable object-oriented code. Each letter in SOLID stands for a principle that solves common software design problems.

1. S - Single Responsibility Principle (SRP)

Meaning: A class should only have one job or reason to change.

Example in C#:


public class InvoicePrinter {
    public void PrintInvoice(Invoice invoice) {
        // Only handles printing logic
    }
}

Use Case: Keep printing logic separate from saving or emailing invoices.

2. O - Open/Closed Principle (OCP)

Meaning: Software should be open for extension but closed for modification.

Example in C#:


public abstract class Shape {
    public abstract double Area();
}

public class Circle : Shape {
    public double Radius { get; set; }
    public override double Area() => Math.PI * Radius * Radius;
}

Use Case: Add new shapes without modifying existing Shape logic.

L - Liskov Substitution Principle (LSP)

Meaning: Subclasses should be usable through the base class interface without breaking the behavior.

Example in C#:


public class Bird {
    public virtual void Fly() { }
}

public class Eagle : Bird {
    public override void Fly() {
        // Flies high
    }
}

Use Case: A flying bird like Eagle should behave like a Bird when used in the system.

I - Interface Segregation Principle (ISP)

Meaning: Don’t force classes to implement methods they don't need.

Example in C#:


public interface IPrint {
    void Print();
}

public interface IScan {
    void Scan();
}

Use Case: A printer that doesn’t support scanning should not be forced to implement a Scan method.

D - Dependency Inversion Principle (DIP)

Meaning: Depend on abstractions, not concrete classes.

Example in C#:


public interface IMessageSender {
    void Send(string message);
}

public class EmailSender : IMessageSender {
    public void Send(string message) {
        // send email
    }
}

public class Notification {
    private readonly IMessageSender _sender;
    public Notification(IMessageSender sender) {
        _sender = sender;
    }

    public void Alert(string msg) {
        _sender.Send(msg);
    }
}

Use Case: Notification can use any kind of message sender (email, SMS, etc.) without changing its code.

Conclusion

Applying SOLID principles makes your C# code easier to understand, test, and maintain. These simple guidelines help create flexible software that can grow and adapt over time without becoming a mess.

Post a Comment

0 Comments