在 Perl OOP 中,在构造函数中是否有任何关于初始化的官方建议? [英] In Perl OOP, is there any official recommendations on initialisation within the constructor?

查看:32
本文介绍了在 Perl OOP 中,在构造函数中是否有任何关于初始化的官方建议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Perl 面向对象编程中,是否有任何官方 [1] 建议在新"构造函数中分离或包含初始化?

In Perl Object Oriented Programming, is there any official[1] recommendations for the separation or inclusion of initialisation in the "new" constructor?

我正在寻找 Perl 最佳实践或类似的参考资料.

I'm seeking references to Perl Best Practices or similar.

例如,是否有关于以下拆分或组合形式的官方建议:

For example is there an official recommendation for the split or combined form of the following:

sub new {
   my ( $obj_or_class ) = @_;

   my $class = ( ref $obj_or_class ) ? ref $obj_or_class : $obj_or_class;
   my $self = bless {}, $class;
   return $self;
} ## end sub new

sub init {
   my ( $self, $arg ) = @_;
      foreach my $key (@VALID_KEYS) {
       if ( exists $arg->{$key} ) {
           $self->{$key} = $arg->{$key};
       }
   }
   return;
} ## end sub _init

[1] 我意识到 Perl 社区中的官方"是一个非常松散的概念.

[1] I realise "official" within the Perl community is a pretty loose concept.

推荐答案

基本上,构造函数返回一个受祝福的对象,然后一个方法对该对象进行操作.一个简单的判断方法是查看第一个参数.它是名为 $class 还是 $self ?

Basically, a constructor returns a blessed object, and a method operates on that object. An easy way to tell is to look at the first parameter. Is it named $class or $self?

通常的做法是调用充当构造函数的子例程作为 new.这很容易弄清楚.此外,通常的做法是将构造函数放在包中的方法之前.

It is common practice to call the subroutine that acts a constructor as new. This makes it easy to figure it out. Also, it's common practice to put the constructors first in your package before the methods.

在真正的 Perl 中,您没有任何东西可以强制执行这些操作.我最喜欢的是inside-out classes,它们很受欢迎,因为你不能cheat 使用类作为引用.这是 Perl 对私有方法的回答.对我来说,它使编程和调试变得不可能进行和维护.

In real Perl, you have nothing that enforces any of this. My favorite are inside-out classes which are popular because you can't cheat by using classes as references. It's Perl's answer to private methods. To me, it makes programming and debugging impossible to do, and maintain.

当然,最新的方法不是自己滚动,而是使用Moose,或Mouse,或众多衍生产品之一.驼鹿.您甚至可以使用 Class::Struct 与所有其他模块不同的是标准 Perl模块.

Of course, the latest way is to not roll your own, but to use Moose, or Mouse, or one of the many derivatives. of Moose. You can even use Class::Struct which unlike all of the other modules is a standard Perl module.

这篇关于在 Perl OOP 中,在构造函数中是否有任何关于初始化的官方建议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆