Using Getters and Setters:
When you define a property for a class, a general purpose getter and
setter are created for you. However, you can create your own getter and
setter for a property. A Getter for a property is used to retrieve the value of
a property. A Setter for a property is used to set the value of the property.
Getting and Setting a Property:
Before you define your own getters and setters, you should become familiar with
the helper procedures: GetProperty and SetProperty.
GetProperty:
The GetProperty procedure is used to get the value of a property for a specific
object. Note using the GetProperty procedure does not run the "Getter"
procedure for the property. It is designed to be used within a user defined
Getter, and should not be used in other circumstances. The GetProperty
procedure takes three arguments: The Class of the Object, The Name of the
Object, and the Property.
For instance, in our Rectangle Class, we could retrieve the Width of R1 by
entering.
? show GetProperty "Rectangle "R1 "Width
120
SetProperty:
The SetProperty procedure is used to set the value of a property for a specific
object. Note using the SetProperty procedure does not run the "Setter"
procedure for the property. It is designed to be used within a user defined
Setter, and should not be used in other circumstances. The SetProperty
procedure takes four arguments: The Class of the Object, The Name of the
Object, the Property to set, and the value to set the property to.
So we could set the Width of R1 be entering:
? SetProperty "Rectangle "R1 "Width 250
? show r1.width
250
Creating your own Getter and Setters:
OK, now we have the tools necessary to create our own Getter and Setter. Let's
create a small class for demostration purposes called Circle. The Circle will
have one property called radius. We will create our own getter and setter for
the radius so we can ensure whatever radius is set to is a number.
The DefineProperty procedure we have used throughout our exercises, actually
has two default arguments: the Getter and Setter for the property. So far, we
haven't used these arguments so the getter and setter for the property was
created for us.
Getter:
The Getter for a property should always output a value. If you notice in the
example below we use the :this variable to Get the property of the current
object.
Setter:
The Setter for a property has an automatic argument called :value. This is the
value that the property should be set to. Again in our example below we use the
:this variable to Set the property of the current object.
Now, we will create our own Getter and Setter for a property.
? DefineClass "Circle
? (DefineProperty "Circle "Radius [ output GetProperty "Circle :this "Radius] [
ifelse not number? :value [ (throw "error [Radius must be a number!!]) [
SetProperty "Circle :this "Radius :value]])
? newcircle "c1
? c1.SetRadius "Hello
Radius must be a number!!
? c1.SetRadius 100
? show c1.radius
100
|