Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smalltalk initialization variables

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
like image 744
Jeremy Knees Avatar asked Jan 08 '13 21:01

Jeremy Knees


1 Answers

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:

  • We are using the #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).
  • We can define as many class methods as we want to create new 'configured' instances (e.g. Color fromHexa:) or return pre-created ones (e.g. Color blue).
  • You can still create an uninitialized instance by doing 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

like image 126
Andrés Fortier Avatar answered Oct 24 '22 09:10

Andrés Fortier