Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between instances created with and without `new` in GNU Smalltalk

What is the difference between

Rectangle origin: 5@5 extent: 40@30

and

Rectangle new origin: 5@5 extent: 40@30
like image 858
adius Avatar asked Oct 22 '25 15:10

adius


2 Answers

Rectangle new origin: 5@5 extent: 40@30 creates a fully-initialized instance of a Rectangle (to be precise with all coordinates set to 0) and then sets its coordinates and extent with the origin:extend: accessor method.

Rectangle origin: 5@5 extent: 40@30 has the class Rectangle construct a Rectangle instance with the given attributes however it sees fit. In the case of GNU Smalltalk, it uses the basicNew message to allocate the Rectangle instance instead of new (see the source of Rectangle). That forgoes the "fully-initialized instance" state of the variant above: it skips any initialization and just allocates the memory (well, the GNU Smalltalk docs don't say so explicitly, but that is traditionally the purpose of basicNew). Then it uses the origin:extend: accessor to initialize the coordinates and extent of the new instance.

like image 147
JayK Avatar answered Oct 25 '25 13:10

JayK


It's a matter of style. The Rectangle class provides a facility method for creating an instance, so that you can communicate directly with the class and write less code. It's also a good practice as you create the rectangle object with all it needs to work correctly (this practice is called RAII, resource acquisition is initialization). If you have a look at the source of Rectangle class>>#origin:extent: you'll find something very much like

origin: aPoint extent: anotherPoint
    ^self new origin: aPoint extent: anotherPoint

So actually sending the message directly to the class o creating it manually and then setting it is in practice the same

like image 24
melkyades Avatar answered Oct 25 '25 11:10

melkyades