SOLID is an acronym that represents five key principles of object-oriented software design. Following these principles helps developers create robust, maintainable, and scalable systems.
1. S – Single Responsibility Principle (SRP)
A class should have only one reason to change.
-
Each class should do one thing and do it well.
-
Changes in requirements should affect only one class, reducing risk of bugs.
Example:
-
A
ReportGeneratorclass should generate reports, but not handle saving them to disk. Saving can be a separateReportSaverclass.
2. O – Open/Closed Principle (OCP)
Software entities should be open for extension, but closed for modification.
-
You should be able to add new functionality without changing existing code.
-
Achieved via inheritance or interfaces.
Example:
-
A
PaymentProcessorinterface allows adding new payment methods (Credit Card, PayPal) without modifying existing processors.
3. L – Liskov Substitution Principle (LSP)
Subtypes must be replaceable for their base types without affecting correctness.
-
Derived classes should behave consistently with their base class.
-
Prevents unexpected behavior when substituting subclasses.
Example:
-
If
Birdhas aFly()method, a subclassPenguinshould not inherit it if penguins cannot fly. Better to redesign the hierarchy.
4. I – Interface Segregation Principle (ISP)
Clients should not be forced to depend on interfaces they do not use.
-
Split large interfaces into smaller, specific ones.
-
Makes code easier to implement and maintain.
Example:
-
Instead of a
Machineinterface withPrint(),Scan(), andFax(), create separateIPrinter,IScanner,IFaxinterfaces.
5. D – Dependency Inversion Principle (DIP)
High-level modules should not depend on low-level modules. Both should depend on abstractions.
-
Reduces coupling and increases flexibility.
-
Use interfaces or abstract classes to decouple dependencies.
Example:
-
A
ReportServicedepends on anILoggerinterface rather than a concreteFileLogger. You can switch toDatabaseLoggerwithout changingReportService.
Summary
-
SOLID principles help make code clean, flexible, and maintainable.
-
Applying them reduces bugs, simplifies testing, and allows safe changes.
Aucun commentaire:
Enregistrer un commentaire