News for hackers. Stuff that matters.
Re:A Square Is Not A Rectangle by txxxxd on Monday September 14, 2009 @04:15PM (#822515)
"It is perfectly expected that calling setHeight() on a Square will also change its width."

If you're writing code that operates on Rectangles you wouldn't expect setHeight to have the side-effect of changing the width too.

It's only "perfectly expected" if you know about the implementation details of Square, which may not even have existed until after a lot of Rectangle code was already in place.

Re:A Square Is Not A Rectangle by endtime on Monday September 14, 2009 @04:33PM (#822557)
>It's only "perfectly expected" if you know about the implementation details of Square, which may not even have existed until after a lot of Rectangle code was already in place.

I don't quite agree. You don't need to know implementation details of Square (e.g. does SetHeight set the height and call SetWidth, or does it just call SetSide? Or does it, as well as SetWidth, set some new property called side?), you just need to know how a Square differs from a Rectangle (width == height).

Because Squares are a subset of Rectangles, any Rectangle code should also work with Squares. Even without Square, prevents you instantiating a Rectangle and always calling SetWidth(x) and SetHeight(x) one after the other.

Re:A Square Is Not A Rectangle by jhancock on Monday September 14, 2009 @04:25PM (#822539)
your correct. And this is why the example is not good. Your saying someone might not expect the "side effect" of width changing when height changes. But this is a semantic setup. People do know how a Square is supposed to behave. One of the characteristics of a "first class object" is that there is common agreement on behavior. If we don't have this shared agreement, lots of things about OO design fall apart.
Re:A Square Is Not A Rectangle by mattmcknight on Monday September 14, 2009 @05:14PM (#822635)
If the method isn't final, I would consider the possibility of implementation differences in subclasses. I am trying to think of a case where it would cause a problem, and most of those involve methods that probably ought to be in the Rectangle class anyway (and thus could be overridden in square).

To me the cleanest solution is :

setDimensions(height, width)

where the contract for square enforces the equality of height and width.