In languages like Java and C++ we give parameters to constructors.
How do you do this in Pharo Smalltalk?
I want something like
|aColor|
aColor = Color new 'red'.
Or is this bad practice and should I always do
|aColor|
aColor = Color new.
aColor name:= red.d
The short answer is that you can do pretty much the same in Smalltalk. From the calling code it would look like:
The long answer is that in Smalltalk you don’t have constructors, at least not in the sense that you have a special message named after the class. What you do in Smalltalk is defining class-side messages (i.e. messages understood by the class, not the instance[*]) where you can instantiate and configure your instances. Assuming that your
Colorclass has anameinstance variable and a setter for it, the#named:method would be implemented like:Some things to note:
#newmessage sent to the class to create a new instance. You can think of the#newmessage as the primitive way for creating objects (hint: you can browse the implementors of the#newmessage to see how it is implemented).Color fromHexa:) or return pre-created ones (e.g.Color blue).Color new. If you want to forbid that behavior then you must override the#newclass message.There are many good books that you can read about Smalltalk basics at Stef’s Free Online Smalltalk Books
[*] This is quite natural due to the orthogonal nature on Smalltalk, since everything (including classes) is an object. If you are interested check Chapter 13 of Pharo by Example or any other reference to classes and metaclasses in Smalltalk.
HTH