First of all, I noticed that you are not using an explicit attribute for your class.
$self->{price} = 0;
This disrupts much of the encapsulation that Moose uses. The moose solution will at least make the priceactual attribute.
use 5.10.0;
has '_price' => ( is => 'rw' );
sub price {
my ( $self, $item ) = @_;
given ($item) {
when ('A') { $self->_price($PRICE_OF_A) }
default { $self->_price(0) }
}
}
, , ,
, . Kata
,
. , -
ReadOnly.
has pricing_rules => (
isa => 'HashRef',
is => 'ro',
traits => ['Hash'],
default => sub { {} },
handles => {
price => 'get',
has_price => 'exists'
},
);
, , Moose "Native
". Item .
, , ,
. , Kata,
:
is( price(""), 0 );
, .
, , 0.
around 'price' => sub {
my ( $next, $self, $item ) = @_;
return 0 unless $self->has_price($item);
$self->$next($item);
};
, .
has items => (
isa => 'ArrayRef',
traits => ['Array'],
default => sub { [] },
handles => {
scan => 'push',
items => 'elements'
},
);
, " " scan,
.
my $co = Checkout->new( pricing_rules => $RULES );
is( $co->total, 0 );
$co->scan("A");
is( $co->total, 50 );
, total List::Util sum.
sub total {
my ($self) = @_;
my @prices = map { $self->price($_) } $self->items;
return sum( 0, @prices );
}
Kata,
"".
.
{
package Checkout;
use Moose;
our $VERSION = '0.01';
use namespace::autoclean;
use List::Util qw(sum);
has pricing_rules => (
isa => 'HashRef',
is => 'ro',
traits => ['Hash'],
default => sub { {} },
handles => {
price => 'get',
has_price => 'exists'
},
);
around 'price' => sub {
my ( $next, $self, $item ) = @_;
return 0 unless $self->has_price($item);
$self->$next($item);
};
has items => (
isa => 'ArrayRef',
traits => ['Array'],
default => sub { [] },
handles => {
scan => 'push',
items => 'elements'
},
);
sub total {
my ($self) = @_;
my @prices = map { $self->price($_) } $self->items;
return sum( 0, @prices );
}
__PACKAGE__->meta->make_immutable;
}
{
package main;
use 5.10.0;
use Test::More;
our $RULES = { A => 50 };
sub price {
my ($goods) = @_;
my $co = Checkout->new( pricing_rules => $RULES );
for ( split //, $goods ) { $co->scan($_) }
return $co->total;
}
TODO: {
local $TODO = 'Kata 9 not implemented';
is( price(""), 0 );
is( price("A"), 50 );
is( price("AB"), 80 );
is( price("CDBA"), 115 );
is( price("AA"), 100 );
is( price("AAA"), 130 );
is( price("AAAA"), 180 );
is( price("AAAAA"), 230 );
is( price("AAAAAA"), 260 );
is( price("AAAB"), 160 );
is( price("AAABB"), 175 );
is( price("AAABBD"), 190 );
is( price("DABABA"), 190 );
my $co = Checkout->new( pricing_rules => $RULES );
is( $co->total, 0 );
$co->scan("A");
is( $co->total, 50 );
$co->scan("B");
is( $co->total, 80 );
$co->scan("A");
is( $co->total, 130 );
$co->scan("A");
is( $co->total, 160 );
$co->scan("B");
is( $co->total, 175 );
}
done_testing();
}