4 ms·
"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 exp
by txxxxd 17y ago
"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.
- jhancock 17y agoyour 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.
- endtime 17y ago>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.
- mattmcknight 17y agoIf 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.