Hi all,
The article here shows a 'bad' example of code that breaks the LSP:
The code is:
public class Rectangle
{
protected int _width;
protected int _height;
public int Width
{
get { return _width; }
}
public int Height
{
get { return _height; }
}
public virtual void SetWidth(int width)
{
_width = width;
}
public virtual void SetHeight(int height)
{
_height = height;
}
}
public class Square: Rectangle
{
public override void SetWidth(int width)
{
_width = width;
_height = width;
}
public override void SetHeight(int height)
{
_height = height;
_width = _height;
}
}
[TestFixture]
public class RectangleTests
{
[Test]
public void AreaOfRectangle()
{
Rectangle r = new Square();
r.Width = 5;
r.Height = 2;
// Will Fail - r is a square and sets
// width and height equal to each other.
Assert.IsEqual(r.Width * r.Height,10);
}
}
The author says:
Square should not be derived from Rectangle (at least not coded like this with these expectations anyway). But does not show the correct way of implementing Square.
Could anyone help me understand the correct implementation?
TIA
Sheila
The article here shows a 'bad' example of code that breaks the LSP:
The code is:
public class Rectangle
{
protected int _width;
protected int _height;
public int Width
{
get { return _width; }
}
public int Height
{
get { return _height; }
}
public virtual void SetWidth(int width)
{
_width = width;
}
public virtual void SetHeight(int height)
{
_height = height;
}
}
public class Square: Rectangle
{
public override void SetWidth(int width)
{
_width = width;
_height = width;
}
public override void SetHeight(int height)
{
_height = height;
_width = _height;
}
}
[TestFixture]
public class RectangleTests
{
[Test]
public void AreaOfRectangle()
{
Rectangle r = new Square();
r.Width = 5;
r.Height = 2;
// Will Fail - r is a square and sets
// width and height equal to each other.
Assert.IsEqual(r.Width * r.Height,10);
}
}
The author says:
Square should not be derived from Rectangle (at least not coded like this with these expectations anyway). But does not show the correct way of implementing Square.
Could anyone help me understand the correct implementation?
TIA
Sheila