Sobes.tech
Junior — Middle

How to implement and ensure compliance with the Liskov Substitution Principle in object-oriented programming?

sobes.tech AI

Answer from AI

The Liskov Substitution Principle (LSP) states that objects of a subclass should be interchangeable with objects of the superclass without violating the correctness of the program.

To implement and adhere to this principle in object-oriented programming, including in Flutter (Dart), you should:

  • Maintain the behavior of the superclass: the subclass should not alter the expected behavior of the superclass methods. For example, if a superclass method guarantees a certain result or side effects, the subclass should support them.

  • Do not weaken preconditions: subclass methods should not require stricter input conditions than the superclass.

  • Do not strengthen postconditions: subclass methods should guarantee at least the same output guarantees as the superclass.

  • Use interfaces and abstract classes correctly: subclasses should implement all required methods and not break the logic.

Example in Dart:

abstract class Bird {
  void fly();
}

class Sparrow implements Bird {
  @override
  void fly() {
    print('Sparrow is flying');
  }
}

class Ostrich implements Bird {
  @override
  void fly() {
    throw UnsupportedError('Ostrich cannot fly');
  }
}

Here, Ostrich violates LSP because it cannot replace Bird without changing behavior. To adhere to LSP, it is better to separate interfaces:

abstract class Bird {}

abstract class FlyingBird extends Bird {
  void fly();
}

class Sparrow implements FlyingBird {
  @override
  void fly() {
    print('Sparrow is flying');
  }
}

class Ostrich implements Bird {
  // does not implement fly, as it cannot fly
}

Thus, following LSP is achieved through proper design of class and interface hierarchies.

How to implement and ensure compliance with the… - sobes.tech