View · Search · Index
No registered users in community xowiki
in last 10 minutes

Re: [Xotcl] getter

From: Stefan Sobernig <stefan.sobernig_at_wu.ac.at>
Date: Tue, 18 Jan 2011 16:20:28 +0100

Krzysztof;

> I need an example of implementation of a getter.
> I have an attribute in a class which now needs a customized getter.
> Class A -slots {
> Attribute attr -proc get {domain var} {
> #how to get attr value here? if I do [my attr] I get recursive call.
> $attr says that there is no such variable
> }
> }

Remember: in get(), you are in the object scope of the managing object
(the attribute slot) and *not* the managed object which is the actuall
value store, e.g.:
Class A -slots {
   Attribute attr -proc get {domain var} {
     #
     # NB: Here, you are in the scope of the managing object, the value
     # needs to be retrieved from the managed one, i.e. the domain
     # object!
     #
     # $domain instvar $var
     # if {[info exists $var]} {
     # return [incr $var]
     # }
     set value [next]
     return [incr value]
   } -valuecmd {
     #
     # whenenever /domain/.attr is accessed (read), this script is
     # evaluated and the object variable is (re-) set to its return
     # value, i.e.: 0
     #
     set return 0; # do not use "return"!
   }
}

A create a -attr 1
a attr; # yields '1', though one might expect '2'; interaction of
valuecmd + get()
a attr 10
a set attr; # yields '0' --> valuecmd only

Depending on what kind of "refinement" you want to achieve, you may
either replace the original (provided) get() or you go for a method
combination by using [next].

> Another question: should I use -proc get or -proc valuecmd? valuecmd
> does seems to be not called at all.

well, hard to tell as I don't know exactly what you are after. But, my
uneducated guess is that get() is your friend.

valuecmd() & co. are hook methods which are invoked upon in certain
phases of object state access or mutation. while at first sight they
might appear idempotent, they are not:

1. get() is invoked only when you access an object's state through the
attribute interface, e.g.: [a attr]. valuecmd is fired always, whenever
trying to access the object variable, whether through [a attr] or [a set
attr].

2. valuecmd, in contrast to get(), is most importantly a *mutator*, it
will *always* perform a state change, i.e. the result of the valuecmd
script becomes the value of the object variable. well, frankly, you
could write a refining get() in a way that is changes the state, but
this is up to you ;)

while there are more subtle differences (e.g., valuecmd is an [eval]'ed
script, not a proc; the two do interact, as shown above; valuecmd does
not now about its surrounding context, i.e. the domain object, unless
being tricked into), this should get you started, i hope ...

//stefan