In smalltalk, when we create a object by calling new which calls initialize . I want to initialize but with my own parameters(passed at run time). How can I do that.
e.g. Myobjcet new
but how do I pass parameters to this so they get passed to initialize. I am using Pharo.
If I recall, reimplementing class methods new
and initialize
should be avoided.
Instead, you can create your own class method (other than new or initialize) that takes parameters, and use those when creating your new instance. For example in Squeak
look at the class method with:
for class Collection
. It first creates a collection instance, and then adds to the instance the object passed as an argument.
with: anObject
"Answer an instance of me containing anObject."
^ self new
add: anObject;
yourself
Your Pharo
maybe based on Squeak, so you should find the same, or a similar class method for Collection
in your image.
Correctly writing the instantiation and initialization code of complex object hierarchies is tricky in Smalltalk. What is more, the default initialization logic as implemented in Object
is different across different Smalltalk dialects (i.e. Pharo decided to introduce a default initializer, making things worse).
To avoid confusion and to have clear and consistent rules the Seaside team decided to apply the following rules for all their code:
Object-Initialization at Seaside
Also the Seaside code includes Code Critic rules that check for mistakes in the use of the proposed initialization pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With