[<<Previous Entry] [^^Up^^] [Next Entry>>] [Menu] [About The Guide]
There are times when you'd like to provide class users with an
instance variable, but control what happens when it's
read/changed. The ACCESS facility lets you define a method
that's invoked whenever the user tries to get the instance
variable's value. ASSIGN is the equivalent, but the method is
invoked when the user attempts to set the instance variable.
You can define either, neither, or both.
For example:
CLASS Temperature
PROTECT nTemp AS NUMERIC
ACCESS Celsius INLINE self:nTemp
ASSIGN Celsius(nNew) INLINE self:nTemp := nNew
ACCESS Fahrenheit INLINE self:nTemp * 9 / 5 + 32
ASSIGN Fahrenheit(nNew) ;
INLINE self:nTemp := (nNew - 32) / 9 * 5, ;
nNew
ENDCLASS
These methods are invoked automatically by code like:
// accesses:
? "Celsius", oTemp:Celsius
? "Fahrenheit", oTemp:Fahrenheit
MyFunc(oTemp:Celsius)
// assigns:
oTemp:Celsius := -40
oTemp:Fahrenheit := -40 // same temp. as above
Sometimes these "fake" instance variables are known as
calculated or virtual instance variables.
Access/assign can be very useful, for example you can start
with a simple class providing a genuine instance variable,
then change to access/assign without having to change the code
that uses the class.
An assign also provides a convenient place to put error
checking:
CLASS Temperature
PROTECT nTemp AS NUMERIC
ACCESS Celsius INLINE self:nTemp
ASSIGN Celsius(nNew)
ACCESS Fahrenheit INLINE self:nTemp * 9 / 5 + 32
ASSIGN Fahrenheit(nNew)
ENDCLASS
ASSIGN Celsius(nNew) CLASS Temperature
if IsValid(nNew)
self:nTemp := nNew
else
Error("...")
endif
return nNew // return this if you want multiple assigns
// e.g. x := y := 40 to work as expected
ASSIGN Fahrenheit(nNew) CLASS Temperature
if IsValid(nNew)
self:nTemp := (nNew - 32) / 9 * 5
else
Error("...")
endif
return nNew // return this if you want multiple assigns
// e.g. x := y := 40 to work as expected
Because an access/assign is a method, you can use "super:" if
you wish.
Online resources provided by: http://www.ClipX.Net --- NG 2 HTML conversion by Dave Pearson