1 package Moose::Cookbook::Basics::Recipe9;
3 # ABSTRACT: Operator overloading, subtypes, and coercion
15 use Moose::Util::TypeConstraints;
19 => where { $_ =~ m{^[mf]$}s };
21 has 'gender' => ( is => 'ro', isa => 'Gender', required => 1 );
23 has 'mother' => ( is => 'ro', isa => 'Human' );
24 has 'father' => ( is => 'ro', isa => 'Human' );
26 use overload '+' => \&_overload_add, fallback => 1;
29 my ( $one, $two ) = @_;
31 die('Only male and female humans may create children')
32 if ( $one->gender() eq $two->gender() );
34 my ( $mother, $father )
35 = ( $one->gender eq 'f' ? ( $one, $two ) : ( $two, $one ) );
38 $gender = 'm' if ( rand() >= 0.5 );
49 This Moose cookbook recipe shows how operator overloading, coercion,
50 and sub types can be used to mimic the human reproductive system
51 (well, the selection of genes at least).
55 Our C<Human> class uses operator overloading to allow us to "add" two
56 humans together and produce a child. Our implementation does require
57 that the two objects be of opposite genders. Remember, we're talking
58 about biological reproduction, not marriage.
60 While this example works as-is, we can take it a lot further by adding
61 genes into the mix. We'll add the two genes that control eye color,
62 and use overloading to combine the genes from the parent to model the
65 =head2 What is Operator Overloading?
67 Overloading is I<not> a Moose-specific feature. It's a general OO
68 concept that is implemented in Perl with the C<overload>
69 pragma. Overloading lets objects do something sane when used with
70 Perl's built in operators, like addition (C<+>) or when used as a
73 In this example we overload addition so we can write code like
74 C<$child = $mother + $father>.
78 There are many genes which affect eye color, but there are two which
79 are most important, I<gey> and I<bey2>. We will start by making a
82 =head2 Human::Gene::bey2
84 package Human::Gene::bey2;
87 use Moose::Util::TypeConstraints;
89 type 'bey2_color' => where { $_ =~ m{^(?:brown|blue)$} };
91 has 'color' => ( is => 'ro', isa => 'bey2_color' );
93 This class is trivial, We have a type constraint for the allowed
94 colors, and a C<color> attribute.
96 =head2 Human::Gene::gey
98 package Human::Gene::gey;
101 use Moose::Util::TypeConstraints;
103 type 'gey_color' => where { $_ =~ m{^(?:green|blue)$} };
105 has 'color' => ( is => 'ro', isa => 'gey_color' );
107 This is nearly identical to the C<Humane::Gene::bey2> class, except
108 that the I<gey> gene allows for different colors.
112 We could just give add four attributes (two of each gene) to the
113 C<Human> class, but this is a bit messy. Instead, we'll abstract the
114 genes into a container class, C<Human::EyeColor>. Then a C<Human> can
115 have a single C<eye_color> attribute.
117 package Human::EyeColor;
120 use Moose::Util::TypeConstraints;
122 coerce 'Human::Gene::bey2'
124 => via { Human::Gene::bey2->new( color => $_ ) };
126 coerce 'Human::Gene::gey'
128 => via { Human::Gene::gey->new( color => $_ ) };
130 has [qw( bey2_1 bey2_2 )] =>
131 ( is => 'ro', isa => 'Human::Gene::bey2', coerce => 1 );
133 has [qw( gey_1 gey_2 )] =>
134 ( is => 'ro', isa => 'Human::Gene::gey', coerce => 1 );
136 The eye color class has two of each type of gene. We've also created a
137 coercion for each class that coerces a string into a new object. Note
138 that a coercion will fail if it attempts to coerce a string like
139 "indigo", because that is not a valid color for either type of gene.
141 As an aside, you can see that we can define several identical
142 attributes at once by supply an array reference of names as the first
145 We also need a method to calculate the actual eye color that results
146 from a set of genes. The I<bey2> brown gene is dominant over both blue
147 and green. The I<gey> green gene dominant over blue.
153 if ( $self->bey2_1->color() eq 'brown'
154 or $self->bey2_2->color() eq 'brown' );
157 if ( $self->gey_1->color() eq 'green'
158 or $self->gey_2->color() eq 'green' );
163 We'd like to be able to treat a C<Human::EyeColor> object as a string,
164 so we define a string overloading for the class:
166 use overload '""' => \&color, fallback => 1;
168 Finally, we need to define overloading for addition. That way we can
169 add together to C<Human::EyeColor> objects and get a new one with a
170 new (genetically correct) eye color.
172 use overload '+' => \&_overload_add, fallback => 1;
175 my ( $one, $two ) = @_;
177 my $one_bey2 = 'bey2_' . _rand2();
178 my $two_bey2 = 'bey2_' . _rand2();
180 my $one_gey = 'gey_' . _rand2();
181 my $two_gey = 'gey_' . _rand2();
183 return Human::EyeColor->new(
184 bey2_1 => $one->$one_bey2->color(),
185 bey2_2 => $two->$two_bey2->color(),
186 gey_1 => $one->$one_gey->color(),
187 gey_2 => $two->$two_gey->color(),
192 return 1 + int( rand(2) );
195 When two eye color objects are added together the C<_overload_add()>
196 method will be passed two C<Human::EyeColor> objects. These are the
197 left and right side operands for the C<+> operator. This method
198 returns a new C<Human::EyeColor> object.
200 =head1 ADDING EYE COLOR TO C<Human>s
202 Our original C<Human> class requires just a few changes to incorporate
203 our new C<Human::EyeColor> class.
205 use List::MoreUtils qw( zip );
207 coerce 'Human::EyeColor'
209 => via { my @genes = qw( bey2_1 bey2_2 gey_1 gey_2 );
210 return Human::EyeColor->new( zip( @genes, @{$_} ) ); };
214 isa => 'Human::EyeColor',
219 We also need to modify C<_overload_add()> in the C<Human> class to
220 account for eye color:
224 eye_color => ( $one->eye_color() + $two->eye_color() ),
231 The three techniques we used, overloading, subtypes, and coercion,
232 combine to provide a powerful interface.
234 If you'd like to learn more about overloading, please read the
235 documentation for the L<overload> pragma.
237 To see all the code we created together, take a look at
238 F<t/000_recipes/basics/010_genes.t>.
242 Had this been a real project we'd probably want:
246 =item Better Randomization with Crypt::Random
248 =item Characteristic Base Class
252 =item More Characteristics
254 =item Artificial Life
260 This work is licensed under a Creative Commons Attribution 3.0 Unported License.
262 License details are at: L<http://creativecommons.org/licenses/by/3.0/>