SOLID Principles
S: Single Responsibility Principle
- Every class should have a single responsibility.
- There should never be more than one reason for a class to change.
- Classes should be small.
- Avoid “god classes”.
- Split large classes into smaller classes.
O: Open/Closed Principle
- Classes should be extendable and usable but not modifiable.
- Variables should be protected and methods should be used when modifying them.
Open for extension, but closed for modification. This applies to any code modification, not only overrides.
L: Liskov Substitution Principle
If you have a Shape class and Circle and Square subclasses, code that uses Shape variables instead of Circle or Square variables should be equally correct if you use either subclass object. Otherwise, your code should mention the specific subclass that matches it or have a new class type.
I: Interface Segregation Principle
- Use specific interfaces for specific problems instead of trying to overgeneralize.
- Keep components focused and minimize dependencies.
Not complying with this can lead to situations where you no longer know what your object is and cannot recover cleanly.
D: Dependency Inversion Principle
- High-level modules should not import anything from low-level modules. Both should depend on abstractions such as interfaces.
- Abstractions should not depend on details. Details-concrete implementations-should depend on abstractions.
This means writing your code in a way that facilitates swapping out components when required. It is the most complicated principle because it's extremely hard to know how far to go in generalization or specification. The ultimate goal is to save on developer costs, whether short-term or long-term.