From Agile Principles, Patterns, and Practices in C# by Robert Martin,
Listing 10-1. A violation of LSP causing a violation of OCP
struct Point {double x, y;} public enum ShapeType {square, circle}; public class Shape { private ShapeType type; public Shape(ShapeType t){type = t;} public static void DrawShape(Shape s) { if(s.type == ShapeType.square) (s as Square).Draw(); else if(s.type == ShapeType.circle) (s as Circle).Draw(); } } public class Circle : Shape { private Point center; private double radius; public Circle() : base(ShapeType.circle) {} public void Draw() {/* draws the circle */} } public class Square : Shape { private Point topLeft; private double side; public Square() : base(ShapeType.square) {} public void Draw() {/* draws the square */} }
DrawShape()
violates OCP. It must know about every possible derivative of the Shape class, and it must be changed whenever new derivatives of Shape are created.The fact that
Square
andCircle
cannot be substituted forShape
is a violation of LSP. This violation forced the violation of OCP by DrawShape . Thus, a violation of LSP is a latent violation of OCP.
How does it violate Liskov substitution principle (LSP)?
(In particular, why can Square
and Circle
not be substituted for Shape
?)
How does violation of LSP cause violation of the open-closed principle (OCP)? (I can see it directly violates OCP, but I can't understand how violation of LSP causes violation of OCP.)
Thanks.