15-SOLID Design Principles.pptx
15-SOLID Design Principles.pptx
15-SOLID Design Principles.pptx
class Square() {
int height;
int area() { return height * height; }
}
class Example {
}
• You can easily imagine the Example class growing larger and larger as more
shapes are introduced into the problem domain.
• The addition of an interface to our example helps to overcome the violation
of the open-closed principle.
• An interface allows for infinite future extensions with no need to ever edit
the class again.
• To fix this example, we first create an interface that both the circle and the
square implement
interface Shape {
int area();
}
}
LSP-Liskov Substitution Principle
• The Liskov Substitution Principle states that subclasses should be
substitutable for their base classes.
• This means that, given that class B is a subclass of class A, we should be able
to pass an object of class B to any method that expects an object of class A
and the method should not give any weird output in that case.
• This is the expected behavior, because when we use inheritance, we assume
that the child class inherits everything that the superclass has. The child
class extends the behavior but never narrows it down.
• Therefore, when a class does not obey this principle, it leads to some bugs
that are hard to detect.
Example (Bird)
// Base class Bird
class Bird {
public:
virtual void fly() {
cout << "I can fly!" << endl;
}
virtual void eat() {
cout << "I can eat!" << endl;
}
};
Example (Bird)
// Derived class Swan
class Swan : public Bird {
public:
void fly() override {
cout << "I believe I can fly!" << endl;
}