/
objects.tex
2466 lines (2072 loc) · 82.7 KB
/
objects.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\chapter{Classes and Objects}
\label{objects}
\index{object}
\index{class}
At this point you know how to use functions to organize code and
built-in types to organize data. The next step is to learn
``object-oriented programming,'' which uses programmer-defined types
to organize both code and data.
\index{abstraction}
\index{encapsulation}
When software applications start to grow large, the number of
details to be handled becomes overwhelming. The only
way to manage this complexity is to use abstraction and
encapsulation. Object orientation is a very popular and efficient
way to implement abstraction and encapsulation.
Raku is an {\bf object-oriented programming language}, which means
that it provides features that support object-oriented
programming, which has these defining characteristics:
\index{object-oriented programming}
\begin{itemize}
\item Programs include class and method definitions.
\index{class}
\index{method}
\item Most of the computation is expressed in terms of operations on
objects.
\item Objects often represent things in the real world, and methods
often correspond to the ways things in the real world interact.
\end{itemize}
Object-oriented programming in
Raku is a big topic that may be worth a book by itself (and
there will probably be a book or two on the subject at some point).
This chapter will hopefully do more than just skim the surface
and enable you to create and use objects, but will not
cover some of the details and more advanced features.
\index{OOP (object-oriented programming)}
\index{object-oriented programming (OOP)}
\section{Objects, Methods and Object-Oriented Programming}
\index{object-oriented programming (OOP)}
\index{programming!object-oriented}
Let us start with a high-level nontechnical overview
of object-oriented programming in general and a brief
introduction to the jargon associated with it.
\index{object}
In computer science, an object may loosely describe a memory
location or an entity having a value, and often be referred to
by an identifier. This can be a variable, a data structure,
an array, or possibly even a function. This general meaning
is not the sense that we will use in this chapter.
In object-oriented programming (OOP), the word {\bf object}
has a much more specific meaning: an object is an entity
which often has:
\begin{itemize}
\item An identity (for example its name).
\index{object! behavior}
\item Some properties defining its behavior (in the form of
special functions that are usually called {\bf methods}); this
behavior usually does not change over time and is generally
common to all objects of the same type.
\index{method}
\item A {\bf state} defined by some special variables (called,
depending on the language, attributes, instance data, fields,
or members); the state may change over time and is generally
specific to each object. In Raku, we speak about
{\bf attributes}.
\index{object!state}
\index{object!attribute}
\index{attribute!object}
\end{itemize}
In brief, an object is a set of attributes and methods packed
together.
\index{class}
Objects are usually defined in a kind of code package called
a {\bf class}. A class defines the methods and the nature of
the attributes associated with an object. In Raku, a class makes it
possible to define new types similar to the built-in types
that we have seen before. Very soon, we will start to define
some classes and to use them to create objects.
\index{type!building new type}
\index{invocant}
\index{method}
\index{dot notation}
You already know informally what a method is, as we have
used built-in methods throughout the book. It is a sort of
function with a special postfix syntax using the dot notation
on the invocant. For example, you may invoke the {\tt say}
method on a simple string:
\begin{verbatim}
"foo".say; # -> foo
\end{verbatim}
Note that ``foo'' isn't an object, but a simple string, but
you can invoke the \verb'say' method on it, because Raku
can treat it internally as an object when needed. In some
OOP languages, this implicit conversion of a native type
into an object is sometimes called autoboxing.
\index{autoboxing}
You probably also remember that methods can be chained in a
process where the value returned by a method becomes the
invocant for the next method:
\begin{verbatim}
"foo".uc.say; # -> FOO
my @alphabet = <charlie foxtrot alpha golf echo bravo delta>;
@alphabet.sort.uc.say;
# prints: ALPHA BRAVO CHARLIE DELTA ECHO FOXTROT GOLF
\end{verbatim}
\index{role}
In OOP, methods applicable to objects are usually defined
within classes, often the class that also defined the
object or some other class closely related to it. In Raku,
methods can also be defined in a {\bf role}, which is
another type of code package somewhat resembling to a class,
as we will see later.
\index{black box}
\index{encapsulation}
The basic idea of object-oriented programming is that an
object is a kind of black box that hides its internals
(data and code) from the user; the user can consult or change
the state of an object through the methods. Hiding the
internals of objects is called {\bf encapsulation}. This
often enables a higher-level view and a better data
abstraction than what we have seen so far; this in turns
helps to make programs less buggy (especially large programs).
In addition, OOP usually also offers the following concepts:
\begin{itemize}
\index{polymorphism}
\item {\bf polymorphism}, i.e., the possibility for a function or
a method to do different things depending of the type of
object which calls it;
\index{inheritance}
\item {\bf inheritance}, i.e., the possibility to derive a class from
another class, so that the child class inherits some of
the properties of the {\bf parent class}, which is a powerful tool
for code reuse.
\end{itemize}
We will now study how all these concepts are implemented in Raku.
\section{Programmer-Defined Types}
\label{point}
\index{programmer-defined type}
\index{type!programmer-defined}
We have used many of Raku's built-in types; now we are going
to define a new type. As an example, we will create a type
called {\tt Point2D} that represents a point in
two-dimensional space.
\index{point, mathematical}
\index{two-dimensional space}
In mathematical notation, points are often written in
parentheses with a comma separating the coordinates. For example,
in Cartesian or rectangular coordinates, $(0,0)$ represents
the origin, and $(x,y)$ represents the point $x$ units to the
right and $y$ units up from the origin. $x$ is called
the abscissa of the point, and $y$ the ordinate.
\index{Cartesian coordinates}
\index{coordinates!Cartesian}
\index{coordinates!rectangular}
\index{rectangular coordinates}
There are several ways we might represent points in Raku:
\begin{itemize}
\item We could store the coordinates separately in two
variables, {\tt \$x} and {\tt \$y}.
\item We could store the coordinates as elements in a list,
an array, or a pair.
\item We could create a new type to represent points as
objects.
\end{itemize}
\index{representation}
Creating a new type is a bit more complicated than the
other options, but it has advantages that will be apparent soon.
A programmer-defined type is usually created by a {\bf class}
(or a \emph{role}, but we will come back to that later).
A barebones class definition for a point type looks like this:
\index{class}
\index{object!class}
\index{class!definition}
\index{definition!class}
\index{role}
\index{Point2D class}
\begin{verbatim}
class Point2D {
has $.abscissa; # "x" value
has $.ordinate; # "y" value
}
\end{verbatim}
%
The header indicates that the new class is called {\tt Point2D}.
The body is defining two attributes, i.e., named properties
associated with the class, here the abscissa and ordinate
(or $x$ and $y$ coordinates) of the point.
\index{Point2D class}
\index{class!Point2D}
\index{type object}
Defining a class named {\tt Point2D} creates a {\bf type object}.
The type object is like a factory for creating objects. To create
a point, you call the {\tt new} method on the {\tt Point2D} class:
\begin{verbatim}
my $point = Point2D.new(
abscissa => 3,
ordinate => 4
);
say $point.WHAT; # -> (Point2D)
say $point.isa(Point2D); # -> True
say $point.abscissa; # -> 3
\end{verbatim}
%
\index{isa method}
\index{WHAT}
You can of course create as many points as you wish.
\index{constructor}
\index{new, object constructor}
\index{dot notation}
\index{object!constructor}
The {\tt new} method is called a {\bf constructor} and has not
been defined in this example; this is not needed because
Raku supplies a default {\tt new} constructor method for
every class (we'll see later how). The method invocation
syntax, with the dot notation, is the same as what we have
used throughout the book to invoke built-in methods. You
are not forced to use this constructor; you can also create
your own (and you may name it {\tt new} or something else),
but we will stay with the built-in {\tt new} method for the
time being.
\index{invocation!method}
\index{method invocation}
Creating a new object with a class is called {\bf instantiation},
and the object is an {\bf instance} of the class.
\index{instance}
\index{object!instance}
\index{instantiation}
Every object is an instance of some class, so the terms
``object'' and ``instance'' are interchangeable. But
we will often use ``instance'' to indicate that we are
talking about an object belonging to a programmer-defined type.
\index{type}
\index{programmer-defined type}
\section{Attributes}
\label{attributes}
\index{instance attribute}
\index{attribute!instance}
\index{dot notation}
The attributes that we have defined are properties associated
with the {\tt Point2D} class, but they are specific to the
instance of the class that has been created. They are
instance attributes. If we create another {\tt Point2D} object,
it will also have these attributes, but the values of
these attributes are likely to be different.
Figure~\ref{fig.point2d} shows the result of these assignments.
A state diagram that shows an object and its attributes is
called an {\bf object diagram}.
\index{state diagram}
\index{diagram!state}
\index{object diagram}
\index{diagram!object}
\begin{figure}
\centerline
{\includegraphics[scale=0.8]{figs/point2D.png}}
\caption{Object diagram.}
\label{fig.point2d}
\end{figure}
The variable {\tt \$point} refers to a {\tt Point2D} object,
which contains two attributes.
Each attribute of the {\tt Point2D} class should refer to a
number, but this is not obvious in the current definition of
the class. As it stands right now, we could create a {\tt Point2D}
object with a string for the abscissa, which would not make
much sense. We can improve the class definition by specifying
a numeric type for the attributes:
%
\begin{verbatim}
class Point2D {
has Numeric $.abscissa; # "x" value
has Numeric $.ordinate; # "y" value
}
\end{verbatim}
%
\index{private attribute}
\index{attribute!private}
The instance attributes are private to the class, which means
that they normally cannot be accessed from outside the class:
you would usually need to invoke a method of the class
(i.e., a kind of subroutine defined within the class), to get
their value. However, when an attribute is defined with a dot
as in \verb'$.abscissa':
\begin{verbatim}
has $.abscissa;
\end{verbatim}
%
\index{accessor}
\index{method!accessor}
Raku automatically creates an implicit \emph{accessor} method,
i.e., a method having the same name as the attribute that returns
the value of this attribute. Thus, when we wrote:
\begin{verbatim}
say $point.abscissa; # -> 3
\end{verbatim}
%
we were not accessing directly the {\tt abscissa} attribute of
the \verb'$point' object, but we were really calling the
{\tt abscissa} method on the object, which in turn returned
the value of that attribute.
\index{dot notation}
\index{accessor}
You can use such an accessor with dot notation as part of any
expression. For example:
\begin{verbatim}
my $dist-to-center = sqrt($point.abscissa ** 2 + $point.ordinate ** 2);
\end{verbatim}
%
There is another way to declare an attribute in a class, with
an exclamation mark twigil instead of a dot:
\index{twigil}
\begin{verbatim}
has $!abscissa;
\end{verbatim}
%
\index{attribute!private}
\index{private attribute}
In that case, Raku does not create an implicit accessor method
and the attribute can only be accessed from methods within
the class. Such an attribute is now fully private.
However, if you declare attributes this way, you
will not be able to populate them at object creation with
the default {\tt new} constructor and will need to create your
own constructor (or indirectly modify {\tt new}). So don't try
that for the time being, as you would not be able to do much
with your objects at this point. We'll get back to that later.
\index{attribute!mutable}
\index{attribute!immutable}
By default, object attributes are not mutable; they are read-only.
This means you cannot modify them once the object has been created.
This is fine for some attributes: if an object represents a
person, that person's name and birth date are unlikely to
change. Some other attributes may need to be updated, sometimes
very frequently. In such cases, attributes can be declared
to be mutable with the {\tt is rw} trait:
\index{is rw trait}
\index{trait!is rw}
\begin{verbatim}
class Point2D {
has Numeric $.abscissa is rw; # "x" value
has Numeric $.ordinate is rw; # "y" value
}
\end{verbatim}
%
It is now possible to modify these attributes. For example,
we can change the newly created point's abscissa:
\begin{verbatim}
# First creating a Point2D object:
my $point = Point2D.new(abscissa => 3, ordinate => 4);
say $point; # -> Point2D.new(abscissa => 3, ordinate => 4)
# Now moving the $point object two units to the right:
$point.abscissa = 5;
say $point; # -> Point2D.new(abscissa => 5, ordinate => 4)
\end{verbatim}
\index{class!attribute}
\index{attribute!class}
Almost all of the information presented so far about attributes
has been related to instance attributes, i.e., to properties related to
individual objects. You can also have attributes pertaining
to the whole class, which are named \emph{class attributes}.
They are less common than instance attributes and are declared
with the {\tt my} declarator (instead of {\tt has}). A typical
example of a class attribute would be a counter at the class level
to keep track of the number of objects that have been
instantiated.
\section{Creating Methods}
\index{method}
The simple {\tt Point2D} class and its instance \verb'$point'
are not very useful so far. Let's complete the class definition
with some methods:
\index{Point2D class}
\begin{verbatim}
class Point2D {
has Numeric $.abscissa;
has Numeric $.ordinate;
method coordinates { # accessor to both x and y
return (self.abscissa, self.ordinate)
}
method distance2center {
(self.abscissa ** 2 + self.ordinate ** 2) ** 0.5
}
method polar-coordinates {
my $radius = self.distance2center;
my $theta = atan2 self.ordinate, self.abscissa;
return $radius, $theta;
}
}
\end{verbatim}
We declare three methods in the class:
\begin{itemize}
\item {\tt coordinates}, a simple accessor to the Cartesian
coordinates;
\index{coordinates!Cartesian}
\index{Cartesian coordinates}
\item{\tt distance2center}, a method to compute and return
the distance between the object and the origin;
\index{polar coordinates}
\index{coordinates!polar}
\item{\tt polar-coordinates}, a method to compute the radius
and azimuth (\verb'$theta') of the object in the polar
coordinates system (notice that {\tt polar-coordinates}
invokes the {\tt distance2center} method to find the radius
component of the polar coordinates).
\end{itemize}
\index{invocant}
A method definition is not very different from a subroutine
definition, except that it uses the {\tt method} keyword
instead of the {\tt sub} keyword. This is not a surprise
since a method is essentially a subroutine that is defined
within a class (or a role) and knows about its
\emph{invocant}, i.e., the object that called it and its class.
And, of course, it has a different calling syntax.
\index{method}
\index{method!dispatch}
\index{dispatching methods}
\index{invocation!method}
\index{method invocation}
Another important difference between a subroutine and a method
is that, since there may be several methods with the same name
defined in different classes (or different roles), a method
invocation involves a \emph{dispatch} phase, in
which the object system selects which method to call, usually
based on the class or type of the invocant. However, in
Raku, that difference is blurred by the fact that you can
have multi subroutines, i.e., subroutines with the same name
and a different signature that are also resolved at run time,
depending on the \emph{arity} (number of arguments) and type of
the arguments.
\index{arity}
\index{type}
Within a method definition, {\tt self} refers to the
\emph{invocant}, the object that invoked the method.
There is a short hand for it, \verb'$.', so that we could
write the {\tt coordinates} method as follows:
\index{self}
\begin{verbatim}
method coordinates { # accessor to both x and y
return ($.abscissa, $.ordinate)
}
\end{verbatim}
The two syntax formats, \verb'$.' and {\tt self}, are
essentially equivalent.
There is a third syntactic way of doing it, using an
exclamation mark instead of a dot:
\begin{verbatim}
method coordinates { # accessor to both x and y
return ($!abscissa, $!ordinate)
}
\end{verbatim}
Here, the result would be the same, but this new syntax is
not equivalent: \verb'$.abscissa' is a method invocation,
whereas \verb'$!abscissa' provides direct access to the attribute.
The difference is that \verb'$!abscissa' is available only
within the class (and might be slightly faster), while
the method invocation syntax can be used somewhere else
(for example in another class). We will see in the next section
examples of this distinction and its consequences.
\index{invocation!method}
\index{method invocation}
We can now create an object and call our methods on it:
\begin{verbatim}
my $point = Point2D.new(
abscissa => 4,
ordinate => 3
);
say $point.coordinates; # -> (4 3)
say $point.distance2center; # -> 5
say $point.polar-coordinates; # -> (5 0.643501108793284)
\end{verbatim}
\index{topical variable}
\index{invocant}
You might remember from previous chapters that if you use a method
without naming an explicit invocant, then the method applies to
the \verb'$_' topical variable:
\begin{verbatim}
.say for <one two three>; # -> one two three (each on one line)
\end{verbatim}
\index{for loop}
\index{given statement}
Now that we have created an object with some methods, we can also
take advantage of the same syntax shortcut. For example if we
use {\tt for} or {\tt given} to populate the \verb'$_' topical
variable with the \verb'$point' object, we can write:
\begin{verbatim}
given $point {
say .coordinates; # -> (4 3)
say .distance2center; # -> 5
.polar-coordinates.say; # -> (5 0.643501108793284)
}
\end{verbatim}
As an exercise, you could write a method called
\verb"distance_between_points" that takes two points
as arguments and returns the distance between
them using the Pythagorean theorem.
The methods of our class so far are all \emph{accessors}, which
means they provide a snapshot of some of the invocant's attributes.
If the attributes are mutable (declared with the \verb'is rw'
trait), we can also create some \emph{mutators}, i.e., methods
that can be invoked to change those mutable attributes:
\index{accessor}
\index{mutator}
\begin{verbatim}
class Point2D-mutable {
has Numeric $.abscissa is rw;
has Numeric $.ordinate is rw;
# perhaps the same accessors as in the class definition above
method new-ordinate (Numeric $ord) {
self.ordinate = $ord;
}
}
# Creating the Point2D-mutable object:
my $point = Point2D-mutable.new(abscissa => 3, ordinate => 4);
say $point; # -> Point2D-mutable.new(abscissa => 3, ordinate => 4)
# Modifying the ordinate:
$point.new-ordinate(6);
say $point; # -> Point2D-mutable.new(abscissa => 3, ordinate => 6)
\end{verbatim}
\section{Rectangles and Object Composition}
\label{rectangles}
\index{rectangle}
\index{composition!object}
\index{object!composition}
Sometimes it is obvious what the attributes of an object should be,
but other times you have to make decisions. For example, imagine you
are designing a class to represent rectangles. What attributes would
you use to specify the location and size of a rectangle? You can
ignore angle; to keep things simple, assume that the rectangle's edges
are either vertical or horizontal.
\index{representation}
There are at least two possibilities:
\begin{itemize}
\item You could specify one corner of the rectangle
(or the center), the width, and the height.
\item You could specify two opposing corners.
\end{itemize}
At this point it is hard to say whether either is better than
the other, so we'll implement the first one, just as an example.
\index{Rectangle class}
\index{class!Rectangle}
Here is the class definition:
\begin{verbatim}
class Rectangle {
has Numeric $.width;
has Numeric $.height;
has Point2D $.corner; # lower left vertex
method area { return $.width * $.height }
method top-left { $.corner.abscissa, $.corner.ordinate + $.height; }
# other methods, e.g. for other corners' coordinates, center, etc.
}
\end{verbatim}
%
The new feature compared to the previous {\tt Point2D} class
definition is that the \verb'Rectangle' class can now use the
{\tt Point2D} type created previously for defining the corner
attribute.
The {\tt top-left} method returns the coordinates of
the top left angle of the rectangle. This {\tt top-left}
method gives us an opportunity to explain a bit more
the difference between the \verb'$.' and \verb'$!' twigils. We have
used \verb'$.corner.abscissa' to obtain the abscissa of
the corner, i.e., in effect an accessor invocation. We could
have directly accessed the {\tt corner} and {\tt height}
attributes of the {\tt Rectangle} class and used the following
method definition:
\index{twigil}
\index{invocation!method}
\index{method invocation}
\begin{verbatim}
method top-left { $!corner.abscissa, $!corner.ordinate + $!height; }
\end{verbatim}
But it would not be possible to use \verb'$!corner!abscissa' or
\verb'$.corner!abscissa', because {\tt abscissa} is not an
attribute defined in the {\tt Rectangle} class, and thus cannot
be accessed directly there. You can use direct access
to the attribute (for example with the \verb'$!abscissa' syntax)
only within the class where this attribute is defined,
{\tt Point2D}. So, in {\tt Rectangle}, we need to invoke the
accessor (i.e., the syntax with \verb'$.') for obtaining the
value of the corner abscissa.
We can now create a {\tt Rectangle} object:
\index{rectangle}
\begin{verbatim}
my $start-pt = Point2D.new(abscissa => 4, ordinate => 3);
my $rect = Rectangle.new(corner => $start-pt, height => 10, width => 5);
say "top-left coord.: ", $rect.top-left; # -> top-left coord.: (4 13)
say "Rectangle area: ", $rect.area; # -> Rectangle area: 50
\end{verbatim}
\index{named parameter}
\index{parameter!named}
You might have noticed that the arguments passed to the
{\tt Rectangle.new} constructor are not in the same order as
in the class definition. I did that on purpose
to show that the order is unimportant because we
are using named arguments.
Figure~\ref{fig.rectangle} shows the state of this object.
\begin{figure}
\centerline
{\includegraphics[scale=0.8]{figs/rectangle.png}}
\caption{Object diagram.}
\label{fig.rectangle}
\end{figure}
\index{state diagram}
\index{diagram!state}
\index{object diagram}
\index{diagram!object}
\index{embedded object}
\index{object!embedded}
\index{object!composition}
\index{composition!object}
Using an object as an attribute of another object, possibly
of another class, is called {\bf object composition}. An object
that is an attribute of another object is {\bf embedded}. Object
composition makes it possible to easily define nested layers of
abstraction and is a powerful feature of object-oriented
programming. In our ``geometry'' example, we started to define
a low-level object, a {\tt Point2D} instance, and then used
that point to build a higher level type, {\tt Rectangle}.
\section{Instances as Return Values}
\index{instance!as return value}
\index{return!value}
Methods can return instances of another class. For example,
the {\tt Rectangle} class can have methods returning
instances of {\tt Point2D} for the other corners:
\begin{verbatim}
method top-right-point {
return Point2D.new(
abscissa => $!corner.abscissa + $!width,
ordinate => $!corner.ordinate + $!height
);
}
# other methods for other corners
\end{verbatim}
Notice that we don't even bother to give a name to upper right
point (although we could, if we wanted); we create it with the
constructor and return it on the fly.
We can use the new method as follows:
\begin{verbatim}
my $topRightPt = $rect.top-right-point;
say "Top right corner: ", $topRightPt;
# -> Top right corner: Point2D.new(abscissa => 9, ordinate => 13)
\end{verbatim}
\index{type}
Although this is not very useful in such a simple case, we
could play it safe and declare a {\tt Point2D} type for
\verb'$topRightPt':
\begin{verbatim}
my Point2D $topRightPt = $rect.top-right-point;
\end{verbatim}
This way, the code will raise an error if the {\tt top-right-point}
happens to return something other than a {\tt Point2D} instance.
Similarly, the \verb"find-center" method invoked on a
{\tt Rectangle} returns a {\tt Point2D} instance
representing the center of the {\tt Rectangle}:
\begin{verbatim}
method find-center { Point2D.new(
abscissa => $!corner.abscissa + $!width / 2,
ordinate => $!corner.ordinate + $!height / 2
);
}
\end{verbatim}
%
This new method can be used as follows:
\begin{verbatim}
say "Center = ", $rect.find-center;
# -> Center = Point2D.new(abscissa => 6.5, ordinate => 8.0)
\end{verbatim}
%
\section{Inheritance}
\index{inheritance}
\index{inheritance!class}
\index{class!inheritance}
Inheritance is probably the most emblematic feature of
object-oriented programming. It is a mechanism through which it
is possible to derive a class from another class. Inheritance is
one of the standard ways to implement code reuse in
object-oriented programming. It is also another useful way of
defining successive layers of abstraction and a hierarchy of
types.
\subsection{The Pixel Class}
\index{class!Pixel}
\index{Pixel class}
The {\tt Point2D} class is very general and could be used for
a variety of purposes: geometry, vector graphics, animated mangas,
and so on. We may want to use it to display graphic data on a
screen. For this scenario, let's create a new derived class,
{\tt Pixel}, adding new properties to the point, such as color,
perhaps transparency, etc.
Do we need to redefine all the attributes and methods for
the new class? No, we don't. We can define a new class that
\emph{inherits} the properties of the {\tt Point2D} base class
and only modify what is no longer suitable or add whatever
new features we need. Here, we want a new attribute to represent
the pixel color and probably some new methods dealing with this
new attribute.
According to the most common standards, a color is defined
by three integers (really three octets, i.e., integers
between 0 and 255 in decimal notation), representing the red,
green, and blue (RGB) components of the pixel:
\index{class!child}
\index{Pixel class}
\index{RGB}
\index{octet}
\begin{verbatim}
class Pixel is Point2D {
has %.color is rw;
method change_color(%hue) {
self.color = %hue
}
method change_color2(Int $red, Int $green, Int $blue) {
# signature using positional parameters
self.color = (red => $red, green => $green, blue => $blue)
}
}
\end{verbatim}
\index{parameter!positional}
\index{parameter!named}
\index{positional parameter}
\index{octet}
\index{is!subclassing trait}
The new class \emph{inherits} the properties of {\tt Point2D}
thanks to the {\tt is Point2D} trait, except possibly those
that are explicitly modified (or overridden) or added in
the new class. The new class is sometimes called a
child class or subclass, whereas {\tt Point2D} is the
parent class. Creating this new class based on
{\tt Point2D} is called {\bf subclassing} the {\tt Point2D}
parent class.
\index{class!parent}
\index{class!child}
\index{class!subclass}
\index{subclassing}
\index{overriding a method}
\index{method!overriding}
The new child class inherits the {\tt abscissa} and
{\tt ordinate} attributes of the {\tt Point2D} parent
class (and their specific type and properties if any),
as well as the methods such as {\tt coordinates} defined
in the parent class. The child class has a new
attribute (the color) and two new methods.
Instantiating a {\tt Pixel} object is just about as easy as
before, we only need to add an additional attribute parameter
in the call to the {\tt new} constructor:
\begin{verbatim}
my $pix = Pixel.new(
:abscissa(3.3),
:ordinate(4.2),
color => {red => 34, green => 233, blue => 145},
);
say "The original pixel has the following colors: ", $pix.color;
\end{verbatim}
In the {\tt Pixel} class definition, we have written
two different methods for changing the color
only to illustrate two possible syntax formats, for pedagogical
purposes. The first one receives a hash as a parameter, and
the second one uses positional parameters, which forces
the user to remember the order (RGB) in which the arguments must
be passed; this can be a source of error and should be avoided
when the number of parameters exceeds a certain limit
(which will be left up to the reader). On the other
hand, anyone working commonly with graphics knows by heart the
standard conventional order of colors (i.e., RGB). Also,
the second method has the
advantage of enabling some type checks (the arguments must
be integers). This is a simplified example; in real life, it
may be desirable to check that the parameters are octets, i.e.,
integers between 0 and 255 (which could be done by adding a
type constraint or defining a subset of the integer type).
\index{subset}
\index{RGB}
\index{octet}
Using the new {\tt Pixel} class is straight forward:
\begin{verbatim}
say "Original colors: ", $pix.color;
$pix.change_color({:red(195), :green(110), :blue(70),});
say "Modified colors: ", $pix.color;
say "New pixel caracteristics:";
printf "\tAbscissa: %.2f\n\tOrdinate: %.2f\n\tColors: R: %d, G: %d, B: %d\n",
$pix.abscissa, $pix.ordinate,
$pix.color<red>, $pix.color{"green"}, $pix.color{"blue"};
$pix.change_color2(90, 180, 30); # positional args
say "New colors:
\tR: {$pix.color<red>}, G: {$pix.color<green>}, B: {$pix.color<blue>} ";
\end{verbatim}
This displays the following output:
\begin{verbatim}
Original colors: {blue => 145, green => 233, red => 34}
Modified colors: {blue => 70, green => 110, red => 195}
New pixel caracteristics:
Abscissa: 3.30
Ordinate: 4.20
Colors: R: 195, G: 110, B: 70
New colors:
R: 90, G: 180, B: 30
\end{verbatim}
To tell the truth, it was not necessary to use two different
method names, \verb'change_color' and \verb'change_color2', as
we did in the {\tt Pixel} class definition to simplify matters.
It would work the same way if we use these definitions:
\index{Pixel class}
\index{method dispatch}
\begin{verbatim}
multi method change_color(%hue) {
self.color = %hue
}
multi method change_color(Int $red, Int $green, Int $blue) {
# signature using positional parameters
self.color = (red => $red, green => $green, blue => $blue)
}
\end{verbatim}
Since the multi method is defined twice, with the same name but
with a different signature, the object system is able to
dispatch the invocation to the right method.
\index{method!dispatch}
\index{multi method}
\subsection{The MovablePoint Class}
\index{class!MovablePoint}
\index{MovablePoint class}
The \verb'$.abscissa' and \verb'$.ordinate' attributes of
class {\tt Point2D} are defaulted to read-only. After all,
when you define a point in the plan, it usually has a fixed
position and there is generally no reason to change its
coordinates.
Suppose, however, that our application is about kinematics
(the branch of physics dealing with the motion of points or
bodies) or is a video game. In such a case, we probably want
our points (or sets of points) to move. We need a new class,
{\tt MovablePoint}, enabling the modification of coordinates.
We don't need to redefine all the attributes and methods for
the new class. Again, we can define a new class that
\emph{inherits} the properties of the {\tt Point2D} base class
and only modifies what is no longer suitable or adds whatever
new features we need, for example:
\begin{verbatim}
class MovablePoint is Point2D {
has Numeric $.abscissa is rw;
has Numeric $.ordinate is rw;
method move (Numeric $x, Numeric $y) {
$.abscissa += $x;
$.ordinate += $y;