[Newbies] Delegates, aliases, or ? How to deal with (avoiding)
cdshaffer at acm.org
Wed May 10 20:03:09 UTC 2006
Charles D Hixson wrote:
>I'm trying to translate some C++ code into Sqeak (it's old, and doesn't
>use the stl). One of the first things it does is define a class called
>Vector. This appears to be the same as the FloatArray class...but not
>really the same.
>What I want to do is ... well, it OUGHT to be subclassing of FloatArray,
>but that class uses a bunch of primitive operations, so I can't really
>tell all that it's doing. Still...
>The main thing I'm doing here is the same thing that's being done in
>FloatArray, but with different names for the operations. So I usually
>want to use the new names as labels for the old operation.
>Is there a better way to do this than just subclass FloatArray and have
>each new method return the old method's calculation?
>When I get to Matrix, not only does it have the same name as an existing
>class (of which it apparently *ought* to be a subclass), but it
>implements methods like +, where Matrix says add: doNotImplement.
I wouldn't subclass FloatArray. Instead I'd create a class Vector with
an instance varaible (probably of type FloatArray) and delegate method
in Vector to the object held by the ivar. This is the classic "adapter"
pattern. Most of your methods will be trivial resends but this will
give you a chance to deal with more significant differences between your
"Vector" and Squeak's FloatArray.
As for your Matrix problem...a couple points:
1) Name conflicts are not uncommon. I prefix my class names with two
letter project identifiers (SCMatrix, for example). Yes it is ugly but
Squeak doesn't currently have namespaces so its all we've got.
2) The reason Matrix>>add: is a shouldNotImplement is because add:
doesn't mean what you think. It means add in the collection since, that
is, add an element to the matrix which makes no sense. Matrix does have
an implementation of the + method (through its superclass) so the
following code works as expected:
m1 := Matrix rows: 3 columns: 2 contents: #(1 2 3 0 9 8).
m2 := Matrix rows: 3 columns: 2 contents: #(4 5 6 7 8 9).
m1 + m2
Again, I'd suggest an adapter class if you want to preserve the API of
your C++ classes in your Smalltalk code.
Hope this helps...
More information about the Beginners