Bird
Raised Fist0
LLDsystem_design~25 mins

Liskov Substitution Principle in LLD - System Design Exercise

Choose your learning style10 modes available
Design: Liskov Substitution Principle Demonstration System
In scope: Designing class hierarchies and interfaces to illustrate LSP, testing substitutability. Out of scope: Implementation in specific programming languages, performance optimization, integration with external systems.
Functional Requirements
FR1: Design a system to demonstrate the Liskov Substitution Principle (LSP) in object-oriented design.
FR2: The system should allow substituting derived classes wherever base classes are expected without altering correctness.
FR3: Include examples of classes that follow LSP and classes that violate LSP.
FR4: Provide a way to test or verify that substitutability holds for compliant classes.
FR5: Support clear separation of behaviors to illustrate correct and incorrect inheritance.
Non-Functional Requirements
NFR1: The design must be simple and understandable for beginners.
NFR2: Focus on clarity over complexity; no need for large-scale system.
NFR3: Use standard object-oriented design concepts.
NFR4: Ensure the design can be extended to add more examples of LSP compliance or violation.
Think Before You Design
Questions to Ask
❓ Question 1
❓ Question 2
❓ Question 3
❓ Question 4
❓ Question 5
Key Components
Base class or interface defining common behavior
Derived classes implementing or extending base behavior
Test module to verify substitutability
Example classes that violate LSP for contrast
Design Patterns
Inheritance and polymorphism
Interface segregation
Design by contract
Substitutability testing
Reference Architecture
 +---------------------+       +---------------------+       +---------------------+
 |      BaseClass      |<------|   DerivedClassGood   |       |  DerivedClassBad    |
 |  (defines behavior) |       | (follows LSP rules)  |       | (violates LSP rules) |
 +---------------------+       +---------------------+       +---------------------+
           ^                             ^                             ^
           |                             |                             |
           +-----------------------------+-----------------------------+
                                         |
                               +---------------------+
                               |   Substitutability   |
                               |       Tester         |
                               +---------------------+
Components
BaseClass
Abstract class or interface
Defines the common behavior that derived classes must implement or extend.
DerivedClassGood
Concrete class
Implements BaseClass behavior correctly, ensuring substitutability without breaking expectations.
DerivedClassBad
Concrete class
Implements BaseClass but violates LSP by changing expected behavior or throwing unexpected exceptions.
Substitutability Tester
Test module or component
Runs tests to verify that instances of DerivedClassGood can replace BaseClass instances without errors, and detects violations in DerivedClassBad.
Request Flow
1. Client code depends on BaseClass interface or abstract class.
2. Client creates instances of DerivedClassGood or DerivedClassBad but treats them as BaseClass.
3. Substitutability Tester runs operations defined in BaseClass on these instances.
4. For DerivedClassGood, operations succeed and results meet expectations.
5. For DerivedClassBad, operations fail or produce incorrect results, indicating LSP violation.
6. Tester reports compliance or violation based on observed behavior.
Database Schema
Not applicable; this design focuses on class hierarchies and behavior rather than data storage.
Scaling Discussion
Bottlenecks
Adding many derived classes can make testing substitutability complex.
Complex behaviors in derived classes may obscure LSP violations.
Manual testing may miss subtle violations in large hierarchies.
Solutions
Automate substitutability tests with unit testing frameworks.
Use design by contract to specify preconditions and postconditions for methods.
Apply static analysis tools to detect potential LSP violations.
Modularize tests to isolate behavior of each derived class.
Interview Tips
Time: Spend 10 minutes explaining LSP concept and importance, 15 minutes designing class hierarchy and test approach, 10 minutes discussing examples of compliance and violation, 10 minutes on scaling and testing strategies.
Explain LSP as a principle ensuring derived classes can replace base classes without breaking correctness.
Show clear class hierarchy with base and derived classes.
Demonstrate how substitutability is tested.
Discuss examples of both compliance and violation.
Highlight importance of testing and design by contract.
Mention how to scale testing for larger systems.

Practice

(1/5)
1.

What does the Liskov Substitution Principle (LSP) primarily ensure in system design?

easy
A. Child classes can replace parent classes without affecting correctness
B. Parent classes must never be extended
C. Child classes should have fewer methods than parent classes
D. Parent classes should depend on child classes

Solution

  1. Step 1: Understand LSP definition

    LSP states that objects of a child class should be replaceable with objects of the parent class without breaking the program.
  2. Step 2: Analyze options against LSP

    Only Child classes can replace parent classes without affecting correctness correctly describes this principle. Other options contradict LSP or are unrelated.
  3. Final Answer:

    Child classes can replace parent classes without affecting correctness -> Option A
  4. Quick Check:

    Liskov Substitution Principle = Child replaces Parent [OK]
Hint: LSP means child works anywhere parent is expected [OK]
Common Mistakes:
  • Thinking LSP forbids inheritance
  • Confusing LSP with interface segregation
  • Believing child classes can change parent behavior arbitrarily
2.

Which of the following class declarations follows the Liskov Substitution Principle?

class Bird {
  fly() {}
}

class Penguin extends Bird {
  fly() {
    throw new Error('Cannot fly');
  }
}
easy
A. Yes, because Penguin is a Bird
B. No, because Penguin breaks expected behavior of Bird
C. Yes, because Penguin overrides fly method
D. No, because Bird should not have fly method

Solution

  1. Step 1: Analyze Penguin's fly method

    Penguin throws an error on fly(), but Bird expects fly() to work normally.
  2. Step 2: Check LSP compliance

    Since Penguin cannot be used where Bird is expected (fly method fails), it violates LSP.
  3. Final Answer:

    No, because Penguin breaks expected behavior of Bird -> Option B
  4. Quick Check:

    Child must not break parent behavior = No [OK]
Hint: Child must not break parent's expected methods [OK]
Common Mistakes:
  • Ignoring method behavior changes in child
  • Assuming inheritance alone guarantees LSP
  • Thinking overriding with error is allowed
3.

Consider the following code snippet. What will be the output?

class Vehicle {
  start() { return 'Vehicle started'; }
}

class Car extends Vehicle {
  start() { return 'Car started'; }
}

function startVehicle(v) {
  return v.start();
}

const myCar = new Car();
console.log(startVehicle(myCar));
medium
A. 'Vehicle started'
B. Error: start is not a function
C. 'Car started'
D. undefined

Solution

  1. Step 1: Understand method overriding

    Car overrides start() method to return 'Car started'.
  2. Step 2: Trace function call

    startVehicle(myCar) calls myCar.start(), which returns 'Car started'.
  3. Final Answer:

    'Car started' -> Option C
  4. Quick Check:

    Overridden method returns child's message [OK]
Hint: Child method overrides parent, so child's output shows [OK]
Common Mistakes:
  • Expecting parent method output instead of child's
  • Confusing method names or forgetting override
  • Assuming error due to polymorphism
4.

Identify the violation of Liskov Substitution Principle in the code below and select the fix.

class Rectangle {
  setWidth(w) { this.width = w; }
  setHeight(h) { this.height = h; }
  area() { return this.width * this.height; }
}

class Square extends Rectangle {
  setWidth(w) {
    this.width = w;
    this.height = w;
  }
  setHeight(h) {
    this.width = h;
    this.height = h;
  }
}
medium
A. Use separate classes without inheritance for Square and Rectangle
B. Square should not override setWidth and setHeight
C. Square should only override area() method
D. No violation, code is correct

Solution

  1. Step 1: Identify LSP violation

    Square changes behavior of setWidth and setHeight, breaking Rectangle's expectations.
  2. Step 2: Choose fix

    To follow LSP, Square and Rectangle should not be in inheritance relation if behaviors differ fundamentally.
  3. Final Answer:

    Use separate classes without inheritance for Square and Rectangle -> Option A
  4. Quick Check:

    Different behavior means no inheritance [OK]
Hint: If child changes parent's method meaning, avoid inheritance [OK]
Common Mistakes:
  • Ignoring behavioral changes in overridden methods
  • Trying to fix by only overriding area()
  • Assuming inheritance always fits shapes
5.

You are designing a payment system with a base class PaymentMethod and subclasses CreditCard and Bitcoin. The base class has a method processPayment(amount) that returns a success message. However, Bitcoin payments require additional confirmation steps and may fail differently. How should you design these classes to follow the Liskov Substitution Principle?

hard
A. Make processPayment abstract and force subclasses to implement their own versions ignoring base behavior
B. Make Bitcoin inherit PaymentMethod and override processPayment to throw errors on failure
C. Remove inheritance and implement separate interfaces for each payment type
D. Keep Bitcoin and CreditCard as subclasses but ensure processPayment behaves consistently and returns success/failure uniformly

Solution

  1. Step 1: Understand LSP in payment context

    Subclasses must behave so they can replace base class without breaking client code.
  2. Step 2: Design consistent behavior

    Bitcoin and CreditCard should implement processPayment so it returns success/failure in a consistent way, hiding internal differences.
  3. Final Answer:

    Keep Bitcoin and CreditCard as subclasses but ensure processPayment behaves consistently and returns success/failure uniformly -> Option D
  4. Quick Check:

    Consistent behavior across subclasses = LSP compliance [OK]
Hint: Subclasses must behave consistently to replace parent safely [OK]
Common Mistakes:
  • Throwing errors breaking expected method contracts
  • Ignoring different failure modes without abstraction
  • Removing inheritance unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard