Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Liskov Subsutution bad example #76

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
91 changes: 48 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2037,58 +2037,63 @@ get into trouble.
**Bad:**

```csharp
using System;
using System.Collections.Generic;

class Rectangle
{
protected double Width = 0;
protected double Height = 0;

public Drawable Render(double area)
{
// ...
}

public void SetWidth(double width)
{
Width = width;
}
protected double Width = 0;
protected double Height = 0;

public void SetWidth(double width)
{
Width = width;
}

public void SetHeight(double height)
{
Height = height;
}
public void SetHeight(double height)
{
Height = height;
}

public double GetArea()
{
return Width * Height;
}
public double GetArea()
{
return Width * Height;
}
}

class Square : Rectangle
{
public double SetWidth(double width)
{
Width = Height = width;
}

public double SetHeight(double height)
{
Width = Height = height;
}
public void SetLength(double length)
{
Width = length;
Height = length;
}
}

public class Program
{
public static void Main()
{
IList<Rectangle> list = new List<Rectangle>()
{new Square(), new Rectangle(), new Rectangle()};
foreach (Rectangle rectangle in list)
{
if (rectangle is Rectangle)
{
rectangle.SetHeight(4);
rectangle.SetWidth(5);
}

if (rectangle is Square)
{
((Square)rectangle).SetLength(5);
}

double area = rectangle.GetArea();
Console.WriteLine(area.ToString());
}
}
}

Drawable RenderLargeRectangles(Rectangle rectangles)
{
foreach (rectangle in rectangles)
{
rectangle.SetWidth(4);
rectangle.SetHeight(5);
var area = rectangle.GetArea(); // BAD: Will return 25 for Square. Should be 20.
rectangle.Render(area);
}
}

var rectangles = new[] { new Rectangle(), new Rectangle(), new Square() };
RenderLargeRectangles(rectangles);
```

**Good:**
Expand Down