From: Peter Duniho on
Arne Vajhøj wrote:
> [...]
>> It's debatable whether one really needs methods in the type that return
>> modified versions of the original. But assuming one does,
>
> It is rather common to have such. The Java API itself has some
> important ones.

Really? Where is the Square type in the Java API that inherits
Rectangle, never mind the immutable version that returns modified
versions of the original?

>> could easily enforce Rectangles and Squares, either by throwing
>> exceptions if misused (which is actually possible even with mutable
>> types, though would involve more work), or by providing methods that
>> always return the right kind of type (Square if the new dimensions are
>> equal, Rectangle otherwise).
>
> What should the formal return type be?

Whatever you want it to be. One option is Rectangle. If it matters
whether the resulting type is a Square (e.g. Rectangle.FitInSquare()),
you can check and cast.

If you want the return type to be Square, you have to throw an exception
if someone tries to return a non-Square from a Square. Or you provide
an API that only returns a Square (e.g. adjusts both dimensions by
identical amounts).

> The sub class can return the super class but not the
> other way around.

Rectangle can return a Square instance and Square can return a
Rectangle. I have no idea why you think you can't do it that way.

Of course, whatever API is chosen, it needs to make sense in context.
But there's no fundamental reason Rectangle can't return a Square.

>> There's no reason for weird behavior to exist. Just don't implement
>> weird behavior. :)
>
> Difficult to avoid if the classes should have rich functionality.

Now you are adding requirements not originally stipulated. No one said
anything about "rich functionality", nor is it even clear what is meant
in the case of the Square/Rectangle example.

Pete