How should I pass objects to subroutines?

拜拜、爱过 提交于 2019-12-07 00:22:23

问题


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' ) ) {
    # ...
}

回答1:


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.




回答2:


Unless you want to change the original data, it's safer to pass the arguments by reference, using method 2:

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

one (\$cache);

sub one {
    my ( $cache ) = @_;
    if (any {!defined @_} $cache { //can expand on this
       croak "missing parameters";
    if ( my $data = $cache->get( 'key_one' ) ) {
    # ...
}


来源:https://stackoverflow.com/questions/9683370/how-should-i-pass-objects-to-subroutines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!