SOLID Principles Examples
SOLID Principles Examples
// Authentication logic
Definition: Classes should be open for extension but closed for modification.
}
// Usage
};
Adding new shapes like Triangle doesn’t require modifying existing code.
L: Liskov Substitution Principle
Example: A subclass should not break the behavior of its parent class.
public class Penguin : Bird // Violates Liskov because Penguins can't fly
// Correct approach
// Usage
Console.WriteLine(penguin.Fly());
I: Interface Segregation Principle
void Print();
void Scan();
Console.WriteLine("Printing...");
Console.WriteLine("Scanning...");
Console.WriteLine("Printing...");
Definition: High-level modules should not depend on low-level modules. Both should depend on
abstractions.
}
// Notification class depends on the abstraction IMessageService
_messageService = messageService;
_messageService.SendMessage(user, message);
// Usage Example
class Program
Key Simplifications:
Removed string returns: Instead of returning strings from SendMessage, I simplified it to just print
directly, making it easier to follow.
Constructor Injection: The Notification class still receives the IMessageService via constructor injection.
This keeps the code simple but still demonstrates the principle.
Notification (high-level module) does not directly depend on EmailService or SMSService (low-level
modules).
We can easily switch out EmailService and SMSService without modifying Notification.