Hi I need to do a small program in Smalltalk, but I am not sure what I am doing wrong. So, I have an abstract class Class1, which has few subclasses for example Class2.
What I want to do is to create object in method Class1 class as a copy of them self, work on it and after return in. I know it is might to sound weird but I am horrible in explanation.
My method looks like this: (value is a variable from Class1)
|temp|
temp:= self DeepCopy.
1 to: temp >> arrayName size do:
[i: | tenp >> arrayName at i: put (temp >> arrayName at: i) + 10].
^temp
This is my first program in Smalltalk and of course it is not working, maybe you know this language and you could help me a little bit.
Thank you
//////////////////////////////////////////////////////////////////// Edit
my method
move: vector
| temp |
temp :=self deepCopy.
1 to: temp points size do:
[:i | temp points at: i put: ( temp points at: i) + vector].
^temp .
And usage
geo_1:=(Triangle new) initialize 10.
geo_2:= geo_1 move: 2@2
If I understand you correctly, what you want is to clone an object, modify the clone, and then return the modified copy. Am I right? If so, let me provide you with some guidance:
You could indeed implement the cloning mechanism using deepCopy
. Note however that case matters in Smalltalk so please don't send the DeepCopy
message because (most likely) it will not exist, use deepCopy
instead:
temp := self deepCopy.
Names are crucial for readability. Therefore, avoid the use of of generic variables such as temp
. In this case I would suggest renaming the temporary to clone
, which better reflects your intention:
| clone |
clone := self deepCopy.
See what I mean? The name clone
on the left tells the reader what you are doing. The expression self deepCopy
tells how you are doing it.
In Smalltalk you access an object property by sending it a message. There is no dot notation or >>
or anything for this. To send an message just leave a space in between:
clone arrayName
As a good friend of mine says, In Smalltalk the send operator is the white space.
Try not to compose keyword messages. Use temporaries instead and give them revealing names:
value := clone arrayName at: i.
clone arrayName at i: put: value + 10
Note that the name value
that I'm using is not a good one because is too generic. If your array contains prices you should use price
instead. If your array contains points, use point
, etc.
Regarding item 3 above, the only way to access an object property from the outside is to send the object a message. In your case, you want to read the points
of your object, so you need to provide a #points
method that answers with the collection of points the object somehow has. For example, if your class has a points
instance variable define a method with that name as
points
^points
(in the items above I've used arrayName
instead because that was the selector you used initially in your question.)