Definition and calculations
Magic!
Here are two straightforward examples. In both cases, all attributes can be entered.
When you modify the width or height, the perimeters and surfaces are recalculated. The reverse is also true: change the surface or perimeter, and the widths and heights will vary accordingly.
Where is the magic?
In both cases, there isn’t any script behind the scenes! All the calculations are defined once for all within the Rectangle class! So here is a great benefit: if you need more forms using these attributes, you won’t need to write any code (just like above).
Let’s see how this is done!
Access to COMPUTED properties
GET
The function gets surface is defined inside the Rectangle class.
Function get surface() -> $surface: Real
$surface:= This.width * this.height
Once the function above has been written, you can now use the surface property as a regular one!
$rect:=cs.Rectangle.new(60; 20)
$surface:=$rect.surface // get the surface property
ALERT("The surface of this rectangle is: "+String($surface))
SET
// this function will be called when surface is modified
Function set surface($surface)
// keep the width-height ratio
$ratio:=This.width/This.height
This.height:=Square root($surface/$ratio)
This.width:=Square root($surface*$ratio)
Once the functions above have been written, you can now modify the surface property as a regular one! The width and height attributes will be adjusted accordingly.
//Let's create a rectangle who's original width and height are 60x20
$rect:=cs.Rectangle.new(60; 20)
$surface:=$rect.surface // get the surface property
ALERT("The surface of this rectangle is: "+String($surface)) // returns 120
// Let's modify the surface
$rect.surface:=1000
// Then display the new width and height
$width:=$rect.width
$height:=$rect.height
ALERT("The rectangle is now: "+String($width)+" x "+String($height)) // returns 54.77 x 18.25
Queries and sorts…
Collections filled with objects of class Rectangle can be queried and sorted using computed properties!
Query sample:
myRectangles:=myRectangles.query("perimeter < 200")
OrderBy sample:
myRectangles:=myRectangles.orderBy("perimeter desc")
…and JSON
When you use an object with computed properties, these properties will be considered when you “stringify” it.
$rect:=cs.Rectangle.new(30; 40)
ALERT(JSON Stringify($rect;*))