Commit | Line | Data |
66b226e5 |
1 | package BankAccount; |
2 | |
3 | use List::Util qw( sum ); |
4 | use Moose; |
5 | |
6 | has balance => ( |
7 | is => 'rw', |
8 | isa => 'Int', |
9 | default => 100, |
10 | trigger => sub { $_[0]->_record_difference( $_[1] ) }, |
11 | ); |
12 | |
13 | has owner => ( |
14 | is => 'rw', |
15 | isa => 'Person', |
16 | weak_ref => 1, |
17 | ); |
18 | |
19 | has history => ( |
20 | is => 'ro', |
21 | isa => 'ArrayRef[Int]', |
22 | default => sub { [] }, |
23 | ); |
24 | |
25 | sub BUILD { |
26 | my $self = shift; |
27 | |
28 | $self->_record_difference( $self->balance ); |
29 | } |
30 | |
31 | sub deposit { |
32 | my $self = shift; |
33 | my $amount = shift; |
34 | |
35 | $self->balance( $self->balance + $amount ); |
36 | } |
37 | |
38 | sub withdraw { |
39 | my $self = shift; |
40 | my $amount = shift; |
41 | |
42 | die "Balance cannot be negative" |
43 | if $self->balance < $amount; |
44 | |
45 | $self->balance( $self->balance - $amount ); |
46 | } |
47 | |
48 | sub _record_difference { |
49 | my $self = shift; |
50 | my $new_value = shift; |
51 | |
52 | my $old_value = sum @{ $self->history }; |
53 | |
54 | push @{ $self->history }, $new_value - ( $old_value || 0 ); |
55 | } |
56 | |
57 | no Moose; |
58 | |
59 | __PACKAGE__->meta->make_immutable; |
60 | |
61 | 1; |