Sobes.tech
Junior — Middle

Can you explain the L principle of SOLID and its significance in code design?

sobes.tech AI

Answer from AI

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

In simpler terms, if class B inherits from class A, then anywhere an object of class A is used, an object of class B can be substituted, and the program should work correctly without changing its behavior.

Design implications:

  • Ensures proper inheritance and polymorphism.
  • Helps avoid unexpected errors when extending functionality.
  • Promotes the creation of flexible and extendable architectures.

Example in C++:

class Bird {
public:
    virtual void fly() {
        // implementation of flying
    }
};

class Sparrow : public Bird {
    // sparrow can fly, all is well
};

class Ostrich : public Bird {
public:
    void fly() override {
        throw std::logic_error("Ostrich cannot fly");
    }
};

Here, Ostrich violates the LSP because the subclass does not support the behavior of the base class. It is better to design the hierarchy differently, for example, by defining an interface for flying birds.