What is "design by contract" and how does it relate to LSP?
Answer
Design by Contract (DbC), introduced by Bertrand Meyer, is a software design approach where components define formal agreements: preconditions (what the caller must guarantee before calling), postconditions (what the callee guarantees after returning), and invariants (properties always true of the object). LSP is directly expressed in DbC terms: a subclass must accept at least as weak preconditions as the parent (can be more permissive but not stricter) and must provide at least as strong postconditions (can guarantee more but not less). If the parent guarantees a sorted list is returned, the subclass must also return a sorted list. DbC makes LSP violations detectable at the specification level before any code is written. Languages like Eiffel have built-in DbC support; others use assertions and runtime checks.
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 What are the conditions for LSP compliance?
- Intermediate How does ISP prevent "fat interfaces"?
- Intermediate What is the difference between DIP and dependency injection containers?