[Grace-core] Summer Plans
Andrew P. Black
black at cs.pdx.edu
Mon Jun 18 10:51:52 PDT 2012
On 15 Jun 2012, at 10:20 , James Noble wrote:
> Kim Bruce wrote:
>
>> I've missed having constructor code to hide temp variables used to get things set up. Occasionally I'll write a method just to limit the scope of these vbles.
>
> Ok - can you give an example?
> Do we need to talk about this?
>
> you can put code inline in an object or class,
> and it will be executed when the object is created
I think that I've just figured out what Kim is saying here. I think that it is:
Using the class construct, there is no place to declare temps that have the lifetime of the constructor method.
Any name that would be declared in the constructor method becomes a field of the object, even though you might
not want it to be one.
For example,
class aRectangle.at (center: Location) width (w:Number) height (h:Number) -> ShapeType {
def topLeft = center - ( (w at h) / 2).
def bottomRight = center + ( (w at h) / 2 )
method ...
method ...
...
}
(I'm assuming that @ is the binary constructor for Locations, and that Locations understand +, -, / etc., as with Smalltalk Points.)
It would be reasonable to use some temps to simplify this code, for example,
def diagonal = w at h
def semiDiagonal = diagonal / 2
However, if I put these defs into the class, they become fields, which I won't want.
This isn't a problem if I use the nested object syntax:
def aRectangle = object {
method at (center: Location) width (w:Number) height (h:Number) -> ShapeType {
def diagonal = w at h
def semiDiagonal = diagonal / 2
return object {
def topLeft = center - semiDiagonal
def bottomRight = center + semiDiagonal
method ...
method ...
...
}
}
}
One way of looking at this is to say that we designed the class syntax to be a shorthand for a particular kind of object in which there was one method (the constructor method) that had as its body a single object constructor. These are common, but certainly don't encompass all constructor objects. The pattern does not provide for constructor objects with multiple methods [ such as at()width()height(), topLeft()bottomRight(), atX()y()width()height() ], or for constructor methods that require a lot of computation before they are ready to return the finished object.
One workaround is to write out the nested objects as I have done above. Another is to make diagonal and semiDiagonal methods rather than fields; this is quite reasonable in this example, since a client might want them anyway. Note, however, that if a method refers to w and h, then w and h will be captured in the environment of the object, and thus the object might take up more storage than is obvious from the fields in the class construct.
Andrew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailhost.cecs.pdx.edu/mailman/private/grace-core/attachments/20120618/3e8fcb57/attachment.html>
More information about the Grace-core
mailing list