Search code examples
perlobjectargumentssubroutine

How should I pass objects to subroutines?


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

Solution

  • 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.