SOLID software design principles are guidelines that help developers create more maintainable, understandable, and flexible code. These principles apply to any object-oriented design, and they aim to reduce the complexity of software development, making it easier to manage and scale.
The acronym SOLID stands for:
- Single Responsibility Principle (SRP): A class should have only one reason to change, meaning it should have only one job or responsibility.
public class Invoice {
public void CalculateTotal() { /* ... */ }
}
public class InvoicePrinter {
public void Print(Invoice invoice) { /* ... */ }
}
public class InvoiceSaver {
public void SaveToFile(Invoice invoice) { /* ... */ }
}
- Open/Closed Principle (OCP): Software entities should be open for extension but closed for modification, allowing the behaviour to be extended without modifying existing code.
public abstract class Shape {
public abstract double Area();
}
public class Rectangle : Shape {
public double Width { get; set; }
public double Height { get; set; }
public override double Area() => Width * Height;
}
public class Circle : Shape {
public double Radius { get; set; }
public override double Area() => Math.PI * Radius * Radius;
}
- Liskov Substitution Principle (LSP): Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.
public class Bird {
public virtual void Fly() { /* ... */ }
}
public class Sparrow : Bird { }
public class Ostrich : Bird {
public override void Fly() {
throw new InvalidOperationException("Ostriches can't fly.");
}
}
- Interface Segregation Principle (ISP): Clients should not be forced to depend on interfaces they do not use, meaning smaller, more specific interfaces are better than a large, general-purpose one.
public interface IPrinter {
void Print();
}
public interface IScanner {
void Scan();
}
public class MultiFunctionPrinter : IPrinter, IScanner {
public void Print() { /* ... */ }
public void Scan() { /* ... */ }
}
public class SimplePrinter : IPrinter {
public void Print() { /* ... */ }
}
- Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules; both should depend on abstractions. Additionally, abstractions should not depend on details, but details should depend on abstractions.
public interface IMessageSender {
void SendMessage(string message);
}
public class EmailSender : IMessageSender {
public void SendMessage(string message) { /* ... */ }
}
public class Notification {
private readonly IMessageSender _messageSender;
public Notification(IMessageSender messageSender) {
_messageSender = messageSender;
}
public void Send(string message) {
_messageSender.SendMessage(message);
}
}
Happy coding.
Comments
Post a Comment