[Grace-core] thinking about private

Andrew P. Black black at cs.pdx.edu
Thu Dec 6 08:30:48 PST 2012


On 6 Dec 2012, at 02:52 , James Noble wrote:

> I've been translating some "E" code into Grace.
> (more on that later)
> 
> One of the cliché's I've come across is class-like functions - 
> that is functions (methods) that translate object.
> 
> In Grace, we're used to things like this:
> 
> method makeFoo {
> return object {
>   def a = ...
>   var b = ...
>   method m {a + b}
> }
> }
> 
> current Grace rules treat those defs as private. 
> 
> But the E code is generally written slightly differently - as far as I can tell,
> equivalent to this Grace code:
> 
> method makeFoo {
> def a = ...
> var b = ...
> return object {
>   method m {a + b}
> }
> }
> 
> that is, "private" defs & vars can be declared in a lexical scope "just outside" the object to which they belong - 
> if we had nested methods, we could declare private methods there too.  These declarations can be seen by the 
> objects they enclose, but not by objects that inherit from those objects.  And of course, this works well for 
> objects created within functions, but not so well for object literals, or classes.  

This is useful if a and be need to be shared by two different objects (both made by makeFoo). This is like pool variables in Smalltalk.  If they are really used only by the single object returned by makeFoo,  then I don't see the advantage in promoting them to the outer scope.  Isn't it better to make them as local as possible?

I do note that if makeFoo has a parameter, then that parameter will have exactly the same scope as a and b.  Accessing such a parameter inside the new object is a pattern that I've used quite a lot.


> So it looks as if we could consider using this kind of coding to represent "private" if we wanted to.
> Except I remember I thought about this earlier, and there was a reason this wouldn't work, but I 
> can't remember what that was - most likely that if we put methods there, they can't call back via 
> self if they're outside the object to which they belong.  This doesn't apply to vars or defs, however...
> 

This is interesting.  Does using temps in the generator function give a Grace programmer a way of getting a reference to a "fresh" object?

method makeFoo {
	def fresh = object {
		method m {a + b}
		method yourself { a }
	}
	method a {fresh}
	method b {some other object}
        registry.add(a)
	fresh
}

Maybe you don't consider fresh to be fresh.

This pattern also gives a third answer to the question you asked last night: how do I initialize a def?   Move the def into the surrounding scope, compute what you need,  and then bind it to a temp.

	Andrew


More information about the Grace-core mailing list