Learning Liskov Substitution Principle

The Liskov Substitution Principle

The Liskov Substitution Principle states that an object may be replaced by a sub-object without breaking the program. This means that everything should work the same even if the sub-object is used instead of the base object.

Exploring Scenarios for the Liskov Substitution Principle

For example, if a car rental company guarantees that its cars have at least two seats, four tires, and use gasoline, then any brand or model of car rented from them should meet these criteria. If a rented car doesn’t meet these guarantees, it’s a violation of the principle.

Similarly, if a retailer guarantees that its chairs are foldable, then any of its chairs, irrespective of material — wood, plastic, or metal — should meet this requirement. If a chair is sold that doesn’t fold, it’s a violation of the principle.

In object-oriented programming, any class that implements an interface should be able to replace another class that uses the same interface without causing any problems. This applies to the base class and all its subclasses.

Importance of the Liskov Substitution Principle

Violating this principle can result in poorly structured code that requires additional checks and special handling for objects of the same type. It can also be a sign that classes have been generalized too early or that their relationships have been established incorrectly. A new subclass may not fit every behavior it inherits.

To identify potential violations of the Liskov Substitution Principle, look for conditional logic in client code, empty methods in subclasses, or unexpected exceptions being thrown from a subclass method. When designing a class hierarchy, keep this principle in mind to ensure that concepts aren’t prematurely generalized.

In the next segment, you’ll update your e-commerce app to comply with the Liskov Substitution Principle.

See forum comments
Download course materials from Github
Previous: Introduction Next: Implementing Liskov Substitution Principle