Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define functions outside of a class using MooseX::Declare?

Tags:

module

perl

moose

I recently started using the module MooseX::Declare. I love it for its syntax. It's elegant and neat. Has anyone come across cases where you would want to write many functions (some of them big) inside a class and the class definition running into pages? Is there any workaround to make the class definition to just have the functions declared and the real function definition outside the class?

What I am look for is something like this -

class BankAccount {
    has 'balance' => ( isa => 'Num', is => 'rw', default => 0 );
    # Functions Declaration.
    method deposit(Num $amount);
    method withdraw(Num $amount);
}

# Function Definition.
method BankAccount::deposit (Num $amount) {
    $self->balance( $self->balance + $amount );
}

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

I can see that there is a way to make the class mutable. Does anyone know how to do it?

like image 262
sachinjsk Avatar asked Feb 02 '09 07:02

sachinjsk


1 Answers

Easy (but needs adding to the doc).

class BankAccount is mutable {
}

As an aside, why are you defining your methods outside the class?

You can just go

class BankAccount is mutable {
    method foo (Int $bar) {
         # do stuff
    }
}
like image 83
Penfold Avatar answered Nov 14 '22 04:11

Penfold