in reply to Re^3: When to Use Object Oriented approach in Perl? (RFC)
in thread When to Use Object Oriented approach in Perl? (RFC)
Which outputs:package Rectangle; use Moo; has height => (is => 'rw'); has width => (is => 'rw'); sub demo { my ($self) = @_; printf "Demo of %s\n", ref $self; $self->show_dimensions; printf "Resetting height => 4, width => 3\n"; $self->height(4); $self->width(3); $self->show_dimensions; printf "area: %d\n", $self->area; $self->show_dimensions; } sub area { my ($self) = @_; $self->{width} * $self->{height}; } sub show_dimensions { my ($self) = @_; printf "height: %s, width: %s\n", $self->{height} || 'undef', $sel +f->{width} || ''; } package Square; use Moo; extends 'Rectangle'; sub area { my ($self) = @_; $self->{height} = $self->{width}; $self->SUPER::area(); } package main; my $rect = Rectangle->new(width => 2, height => 2); my $sq = Square->new(width => 2); $rect->demo; print "\n"; $sq->demo;
The square fails as a stand-in for a rectangle. The is one of the reasons that wise man say Favor Composition Over InheritanceDemo of Rectangle height: 2, width: 2 Resetting height => 4, width => 3 height: 4, width: 3 area: 12 height: 4, width: 3 Demo of Square height: undef, width: 2 Resetting height => 4, width => 3 height: 4, width: 3 area: 9 height: 3, width: 3
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^5: When to Use Object Oriented approach in Perl? (RFC)
by tobyink (Canon) on Sep 06, 2014 at 15:35 UTC |