简体   繁体   English

我可以使用MooseX :: Declare定义类外的函数吗?

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

I recently started using the module MooseX::Declare . 我最近开始使用模块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? 有谁知道怎么做?

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
    }
}

I want my class definition to be short, and to give an abstract idea of what the class is for. 我希望我的类定义简短,并给出一个关于类的用途的抽象概念。 I like the way its been done in C++ where you have an option to define functions inline or outside the class using the scope resolution operator. 我喜欢在C ++中完成它的方式,你可以选择使用范围解析运算符在内部或类外定义函数。 This makes the class definition short and neat. 这使得类定义简洁而整洁。 This is what I am looking for. 这就是我要找的。

Thanks for your time. 谢谢你的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM