Re: OO Concept: Liskov Substitution Principle
- From: Wayne <nospam@xxxxxxxxxxxxxx>
- Date: Fri, 30 May 2008 12:58:39 -0400
howa wrote:
Just read an article talking about the LSP in term of OO design:
http://www.objectmentor.com/resources/articles/lsp.pdf
The article said Rectangle class should not be a superclass of Square
class.
Okay, so how you would design the Rectangle & Square class?
The article did not cover that, so what are your opinion?
Howard
Clearly all Rectangles are not also Squares. Considering LSP,
Squares are not Rectangles either. Rectangles have two
*independent* values, height and width. With a Square the
height and width must be the same. What the article is
saying is that there is no IS-A relationship between
Squares and Rectangles.
Look at the java.lang.Integer and Double classes. These have
the same issues, in that you might think all Integers are
Doubles. But they're not when you consider LSP.
That doesn't mean there is no relationship however. A Rectangle
might be a Square, and any square Rectangle should be convertible
to a Square. Also any Square should be convertible to a Rectangle.
In Java you generally provide xxxValue and isXxx methods for this.
You might try something such as:
public class Rectangle {
private int width, height;
public Rectangle ( int width, int height ) { ... }
public int getWidth () { return width; }
public int getHeight () { return height; }
public void setWidth ( int width ) {
if ( width >= 0 ) this.width = width;
else ...
}
public void setHeight ( int height ) { ... }
public boolean isSquare () { return width == height; }
public Square squareValue () {
if ( isSquare() ) return new Square( height ); }
else ...
}
}
public class Square {
private int side;
public Square ( int side ) { ... }
public int getHeight () { return side; }
public int getWidth () { return side; }
public void setWidth ( int width ) {
if ( width >= 0 )
side = width;
else ...
}
public void setHeight ( int height ) { ... }
public Rectangle rectangleValue () {
return new Rectangle( side, side );
}
}
============================
What do you think of this?
-Wayne
.
- Follow-Ups:
- References:
- OO Concept: Liskov Substitution Principle
- From: howa
- OO Concept: Liskov Substitution Principle
- Prev by Date: Re: Math in Java
- Next by Date: Re: Math in Java
- Previous by thread: Re: OO Concept: Liskov Substitution Principle
- Next by thread: Re: OO Concept: Liskov Substitution Principle
- Index(es):
Relevant Pages
|