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:
aColor := Color named: 'Red'.
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 Color
class has a name
instance variable and a setter for it, the #named:
method would be implemented like:
(class) Color>>named: aName
| color |
color := self new.
color name: aName.
^color.
Some things to note:
#new
message sent to the class to create a new instance. You can think of the #new
message as the primitive way for creating objects (hint: you can browse the implementors of the #new
message 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 #new
class 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
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