Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

47
  • 35
    @m-sharp What if it's an immutable Rectangle such that instead of SetWidth and SetHeight, we have the methods GetWidth and GetHeight instead? Commented Apr 26, 2012 at 19:28
  • 206
    Moral of the story: model your classes based on behaviours not on properties; model your data based on properties and not on behaviours. If it behaves like a duck, it's certainly a bird. Commented May 19, 2012 at 21:43
  • 298
    Well, a square clearly IS a type of rectangle in the real world. Whether we can model this in our code depends on the spec. What the LSP indicates is that subtype behavior should match base type behavior as defined in the base type specification. If the rectangle base type spec says that height and width can be set independently, then LSP says that square cannot be a subtype of rectangle. If the rectangle spec says that a rectangle is immutable, then a square can be a subtype of rectangle. It's all about subtypes maintaining the behavior specified for the base type. Commented Sep 24, 2012 at 15:46
  • 98
    @Pacerier there is no issue if it's immutable. The real issue here is that we are not modeling rectangles, but rather "reshapable rectangles," i.e., rectangles whose width or height can be modified after creation (and we still consider it to be the same object). If we look at the rectangle class in this way, it is clear that a square is not a "reshapable rectangle", because a square cannot be reshaped and still be a square (in general). Mathematically, we don't see the problem because mutability doesn't even make sense in a mathematical context. Commented Jan 20, 2013 at 6:13
  • 30
    I have one question about the principle. Why would be the problem if Square.setWidth(int width) was implemented like this: this.width = width; this.height = width;? In this case it is guaranteed that the width equals the height. Commented Oct 28, 2015 at 0:45