Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new and initialize in smalltalk - how to pass parameters to initialize

Tags:

smalltalk

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.

like image 956
j10 Avatar asked Apr 23 '13 15:04

j10


2 Answers

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.

like image 111
Dave Newman Avatar answered Nov 13 '22 22:11

Dave Newman


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.

like image 23
Lukas Renggli Avatar answered Nov 13 '22 23:11

Lukas Renggli