LSP Violations: Strengthening Preconditions
You'll learn how making a subclass more demanding than its parent breaks the Liskov Substitution Principle and destroys safe substitutability.
The Core Problem
Remember that LSP requires subclasses to honor the behavioral contract of their parent class. One way to violate this principle is by strengthening preconditions—requiring stricter input conditions in the subclass than the parent allows.
When a parent class accepts certain inputs, clients expect any subclass to accept those same inputs. If a subclass suddenly rejects inputs the parent accepted, substituting that subclass breaks existing code.
A Simple Analogy
Imagine a general "Document Processor" that accepts any text file. If you create a specialized "ReportProcessor" subclass that only accepts files over 100 lines, you've strengthened the precondition. Code expecting to process a 50-line document with any processor will fail when given a ReportProcessor, even though it worked fine with the parent class.
Why This Breaks Substitutability
The Liskov Substitution Principle says: "If I can use a Parent here, I should be able to swap in a Child without problems." When a subclass demands stricter inputs:
- Code written against the parent type suddenly fails
- Clients must check what subtype they're dealing with
- Polymorphism becomes unreliable
- You've broken the behavioral contract
If the parent says "I accept values from 1 to 100," the child cannot say "I only accept values from 50 to 100." That's a broken promise.
Detecting the Violation
Watch for subclass methods that:
- Add new validation that rejects previously valid inputs
- Throw exceptions for cases the parent handled
- Require additional setup the parent didn't need
Key Takeaway: A subclass must accept at least everything its parent accepts—strengthening preconditions violates LSP by making the subclass less tolerant than its parent, breaking substitutability.