Introduction to SOLID principles
• S: Single Responsibility Principle (SRP)
• O: Open-closed Principle (OCP)
• L: Liskov substitution Principle (LSP)
• I: Interface Segregation Principle (ISP)
• D: Dependency Inversion Principle (DIP)
Definitions
• S: A class should only have a single responsibility, that is, only changes to one part of the software’s specification should be able to affect the specification of the class.
• O: Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification
• L: Derived classes should be substitutable for their base classes without altering the correctness of the program.
• I: Clients should not be forced to depend on interfaces they do not use. Instead of one large interface, prefer many small, role-specific interfaces.
• D: High-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.
| Principle | Meaning | Example |
|---|---|---|
| S – Single Responsibility Principle (SRP) | A class should have only one reason to change. Each class should focus on a single responsibility. | A UserService handles user logic, while EmailService handles email sending. |
| O – Open/Closed Principle (OCP) | Software entities should be open for extension but closed for modification. | Adding new payment methods by extending a base class PaymentProcessor instead of modifying it. |
| L – Liskov Substitution Principle (LSP) | Subtypes must be substitutable for their base types without breaking functionality. | A Square class should behave correctly when used in place of a Rectangle. |
| I – Interface Segregation Principle (ISP) | Clients should not be forced to depend on interfaces they don’t use. Instead of one large interface, prefer many small ones. | Instead of one large IMachine interface, split into smaller ones like IPrinter, IScanner. |
| D – Dependency Inversion Principle (DIP) | Depend on abstractions, not on concrete implementations. High-level modules should not depend on low-level modules; both should depend on abstractions. | A NotificationService depends on an INotifier interface, which can be implemented by EmailNotifier, SMSNotifier, etc. |
Comments
Post a Comment