What are the conditions for LSP compliance?
Answer
A subclass is LSP-compliant with its parent when it satisfies these behavioral contracts: (1) Preconditions cannot be strengthened — if the parent accepts any integer, the subclass cannot restrict to positive integers only; (2) Postconditions cannot be weakened — if the parent guarantees a non-null return, the subclass cannot return null; (3) Invariants must be preserved — properties that are always true of the parent must remain true in the subclass; (4) No new exceptions — the subclass cannot throw exceptions that the parent doesn't throw (or subtypes of them); (5) History constraint — if the parent's state only changes in certain ways, the subclass must respect those constraints. These conditions together ensure that code using the parent type works correctly with any subtype.
More SOLID Principles Questions
View all →- Intermediate How would you refactor a class that violates SRP?
- Intermediate How does the Strategy pattern support OCP?
- Intermediate How does ISP prevent "fat interfaces"?
- Intermediate What is the difference between DIP and dependency injection containers?
- Intermediate How does SOLID relate to GRASP principles?