From: Pit Capitain Date: 2001-08-16T20:41:09+09:00 Subject: [ruby-talk:19886] Re: Why not?: Assigning to self On 16 Aug 2001, at 18:33, Niklas Frykholm wrote: > On Thu, Aug 16, 2001 at 05:40:48PM +0900, Pit Capitain wrote: > > I just remembered another situation where "become" could be > > useful. I saw it somewhere sometime, but don't remember the > > details. > > > > Take the famous Shape class hierarchy: > > > > class Shape; ...; end > > class Rectangle < Shape; ...; end > > class Square < Rectangle; ...; end > > This is a somewhat problematic hierarchy. Suppose that the Rectangle has a > method set_shape(width, height). The square will inherit it, but it will not > make sense for squares. Why not? In this class hierarchy each square is a (specialized) rectangle, so class Square also has a method #set_shape. If called with width != height, the Square instance would "become" a Rectangle instance. In a drawing program showing a square, why shouldn't it make sense to be able to drag one side or one hotspot in order to change the square into a rectangle? > > > Suppose you have a Rectangle instance and use one of its resizing > > methods so that the new height equals the new width. After that it > > would be nice if the Object had become a Square instance. > > Perhaps, but probably not. It would be very strange when the Rectangle > object suddenly lost its #set_shape method. Everytime you wanted to use > a method on the object, you would have to first figure out whether it > had changed under your feet and become a different object with different > methods. See above. > Or would Rectangle and Square have exactly the same methods? > Then the class would tell you nothing but the current shape of the object > and it would be much better to have an #isSquare method, instead. I can't think of methods for class Square that wouldn't make sense for Rectangle right now, so Square would have the same methods. But they could be implemented differently. For example take a method that returns the axes of reflection of a shape (is this the correct english term?). A rectangle has 2 axes, a square 4. Of course you can implement all this in class Rectangle, using the #isSquare method, but then you would implement polymorphism yourself. > I don't doubt that valid use cases where #become simplifies the design, can > be found. But it seems as something that is all too easy to slap on as a > quick-and-dirty-fix to a problem that has better solutions. Agreed. But as I wrote in my posting, I'd like to have a #become method that is NOT just a dirty implementation. Thanks for your input, Pit