smalltalkgnu-smalltalk

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

Solution

  • 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.