Tag Archives: oop

Objects in Perl (part 2,352)

One of my issues with Perl has always been its implementation of OOP. Or, to be precise, the multitude of ways that a class can be declared (blessed hash, inside-out, Class::Std etc). I would argue that this is a case where TMTOWTDI is not advantageous. Enter Piers Cawley and his _Moose for Ruby Programmers_ talk at the London.pm Technical Meeting, 20th February 2009. MooseX::Declare is yet another way, but check this out…

    use MooseX::Declare;

    class BankAccount {
        has 'balance' => ( isa => 'Num', is => 'rw', default => 0 );

        method deposit (Num $amount) {
            $self->balance( $self->balance + $amount );
        }

        method withdraw (Num $amount) {
            my $current_balance = $self->balance();
            ( $current_balance >= $amount )
                || confess "Account overdrawn";
            $self->balance( $current_balance - $amount );
        }
    }

    class CheckingAccount extends BankAccount {
        has 'overdraft_account' => ( isa => 'BankAccount', is => 'rw' );

        before withdraw (Num $amount) {
            my $overdraft_amount = $amount - $self->balance();
            if ( $self->overdraft_account && $overdraft_amount > 0 ) {
                $self->overdraft_account->withdraw($overdraft_amount);
                $self->deposit($overdraft_amount);
            }
        }
    }

Firstly, yes, that is indeed Perl. Secondly, wow: it actually _looks_ like a class definition. And this was the big win for me, as anyone coming from a Java or PHP background will find it trivial to understand what’s going on here. The main point is that by using MooseX::Declare, you are moving towards a more declarative programming style describing _what_ the program should do rather than _how_ it should achieve it. So, no more unrolling `@_` 🙂

Links

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn