Skip to content

Commit eeeda74

Browse files
authored
Add LSP example with polymorphism to AV1011 (#396)
1 parent ca303e6 commit eeeda74

1 file changed

Lines changed: 53 additions & 1 deletion

File tree

_rules/1011.md

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,56 @@ severity: 2
66
---
77
In other words, you should be able to pass an instance of a derived class wherever its base class is expected, without the callee knowing the derived class. A very notorious example of a violation of this rule is throwing a `NotImplementedException` when overriding methods from a base class. A less subtle example is not honoring the behavior expected by the base class.
88

9-
**Note:** This rule is also known as the Liskov Substitution Principle, one of the [S.O.L.I.D.](https://en.wikipedia.org/wiki/SOLID) principles.
9+
```csharp
10+
// Wrong
11+
public abstract class Shape { }
12+
13+
public class Circle : Shape
14+
{
15+
public double Radius { get; set; }
16+
}
17+
18+
public class Square : Shape
19+
{
20+
public double Side { get; set; }
21+
}
22+
23+
public class ShapeProcessor
24+
{
25+
public double CalculateArea(Shape shape)
26+
{
27+
if (shape is Circle circle)
28+
return Math.PI * circle.Radius * circle.Radius;
29+
30+
if (shape is Square square)
31+
return square.Side * square.Side;
32+
33+
throw new NotSupportedException();
34+
}
35+
}
36+
```
37+
38+
Instead, use polymorphism:
39+
40+
```csharp
41+
public abstract class Shape
42+
{
43+
public abstract double CalculateArea();
44+
}
45+
46+
public class Circle : Shape
47+
{
48+
public double Radius { get; set; }
49+
50+
public override double CalculateArea() => Math.PI * Radius * Radius;
51+
}
52+
53+
public class Square : Shape
54+
{
55+
public double Side { get; set; }
56+
57+
public override double CalculateArea() => Side * Side;
58+
}
59+
```
60+
61+
**Note:** This rule is also known as the Liskov Substitution Principle, one of the [S.O.L.I.D.](http://www.lostechies.com/blogs/chad_myers/archive/2008/03/07/pablo-s-topic-of-the-month-march-solid-principles.aspx) principles.

0 commit comments

Comments
 (0)