我应该如何传递对象的子程序? [英] How should I pass objects to subroutines?

查看:85
本文介绍了我应该如何传递对象的子程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是其中最好的一个或最坏的做法?

使用范围:

 我的$ =缓存智>新建(驱动程序= GT;文件,expires_in => 3600);子有一个{
    如果(我的$数据= $&的cache GT;获取('key_one')){
    #...
}的亚二{
    如果(我的$数据= $&的cache GT;获取('key_two')){
    #...
}

传递对象作为参数:

 我的$ =缓存智>新建(驱动程序= GT;文件,expires_in => 3600);子有一个{
    我($缓存)= @_;
    如果(我的$数据= $&的cache GT;获取('key_one')){
    #...
}的亚二{
    我($参数1,$缓存)= @_;
    如果(我的$数据= $&的cache GT;获取('key_two')){
    #...
}

或在子程序创建一个新的实例

 子有一个{
    我的$ =缓存智>新建(驱动程序= GT;文件,expires_in => 3600);
    如果(我的$数据= $&的cache GT;获取('key_one')){
    #...
}的亚二{
    我的$ =缓存智>新建(驱动程序= GT;文件,expires_in => 3600);
    如果(我的$数据= $&的cache GT;获取('key_two')){
    #...
}


解决方案

第一选择使用一个全局变量,没有这么热。第三个选择是很多额外的开销。没有那么大任,所以我想中间的选择是你的问题的范围内preferable。一个更广泛的问题是,为什么子程序需要了解缓存呢?看样子他们只担心数据。我会考虑获取数据并传递给子程序,他们不必担心,如果它被缓存或刚创建。

Is one of these the best or the worst approach?

utilize the scope:

my $cache = CHI->new( driver => 'File', expires_in => 3600 );

sub one {
    if ( my $data = $cache->get( 'key_one' ) ) {
    # ...
}

sub two {
    if ( my $data = $cache->get( 'key_two' ) ) {
    # ...
}

passing the object as argument:

my $cache = CHI->new( driver => 'File', expires_in => 3600 );

sub one {
    my ( $cache ) = @_;
    if ( my $data = $cache->get( 'key_one' ) ) {
    # ...
}

sub two {
    my ( $argument1, $cache ) = @_;
    if ( my $data = $cache->get( 'key_two' ) ) {
    # ...
}

or creating in the subroutine a new instance:

sub one {
    my $cache = CHI->new( driver => 'File', expires_in => 3600 );
    if ( my $data = $cache->get( 'key_one' ) ) {
    # ...
}

sub two {
    my $cache = CHI->new( driver => 'File', expires_in => 3600 );
    if ( my $data = $cache->get( 'key_two' ) ) {
    # ...
}

解决方案

First choice uses a global variable, not so hot. Third choice is a lot of extra overhead. Not so great either, so I guess the middle choice is preferable within the context of your question. A broader issue is why do the subroutines need to know about the cache at all? It appears they are only worried about the data. I would consider fetching the data and pass that to the subroutines, where they don't have to worry if it was cached or just created.

这篇关于我应该如何传递对象的子程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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