Course of Raku / Objects, I/O, and exceptions / Classes and objects / Methods / Exercises / Rectangle area
Solution: Rectangle area
Here is a possible solution to the task.
Code
class Rectangle {
has $.width;
has $.height;
method area {
$.width * $.height;
}
method describe {
"area is " ~ self.area;
}
}
say Rectangle.new(width => 3, height => 4).describe;🦋 You can find the source code in the file rectangle-area.raku.
Output
area is 12Comments
The
areamethod reads the object’s ownwidthandheightthrough their accessors and multiplies them — for a3by4rectangle, that is12.The
describemethod does not repeat that calculation. Instead it callsself.area, running theareamethod on the same object and reusing its result. Building larger behaviour out of smaller methods this way keeps each method responsible for one job.