我应该如何将对象传递给子程序? [英] How should I pass objects to subroutines?
问题描述
其中一种是最好的还是最差的方法?
Is one of these the best or the worst approach?
利用范围:
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' ) ) {
# ...
}
将对象作为参数传递:
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屋!