I am practising Kata Nine: Back to the CheckOut in Perl whilst also trying to use Moose for the first time.
So far, I’ve created the following class:
package Checkout;
# $Id$
#
use strict;
use warnings;
our $VERSION = '0.01';
use Moose;
use Readonly;
Readonly::Scalar our $PRICE_OF_A => 50;
sub price {
my ( $self, $items ) = @_;
if ( defined $items ) {
$self->{price} = 0;
if ( $items eq 'A' ) {
$self->{price} = $PRICE_OF_A;
}
}
return $self->{price};
}
__PACKAGE__->meta->make_immutable;
no Moose;
1;
The whole price method doesn’t feel very Moose-ish and I feel like this could be refactored further.
Does anyone have any input on how this could be improved?
First thing I noticed is that you’re not using an explicit attribute for your
class.
This violates most of the encapsulation that using Moose provides. A Moose solution
would at the least make
priceinto an actual attribute.However the main problem with the code you’ve presented is that you’re not
really modeling the problem described by the Kata. First the Kata specifically
states that you’ll need to pass in the pricing rules on each invocation of the
Checkout Object. So we know we’ll need to save this state in something other
than a series of ReadOnly class variables.
You’ll see the price method here is now a delegate using Moose’s “Native
Attributes” delegation. This will perform a lookup between an Item and a Rule.
This however won’t handle the case of a lookup on a element that doesn’t
exist. Peeking ahead one of the unit tests the Kata provides is exactly that
kind of a lookup:
So we’ll need to modify the price method slightly to handle that case.
Basically we check to see if we have a price rule, otherwise we return 0.
Next we’ll need to track the items as they’re scanned so we can build a total.
Again the “Native Attributes” delegation provides the
scanmethod that thetest in the Kata are looking for.
Finally a
totalmethod is trivial usingList::Util‘ssumfunction.This code doesn’t fully implement the solution to the Kata, but it does
present a much better model of the problem state and show’s a much more
“Moosey” solution.
The full code and translated tests are presented below.