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' ) ) {
# ...
}
To pass parameters to a subroutine, the calling program pushes them on the stack in the reverse order so that the last parameter to pass is the first one pushed, and the first parameter to pass is the last one pushed. This way the first parameter is on top of the stack and the last one is at the bottom of the stack.
To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.
With internal subroutines, you can use TYPE or LIKE to refer to the internal table you want to pass directly. You can pass all internal tables as parameters in the list after TABLES in the FORM and PERFORM statements. Internal tables passed with TABLES are always called by reference.
C# provides the ref parameter modifier for passing value objects into a method by reference and the out modifier for those cases in which you want to pass in a ref variable without first initializing it. C# also supports the params modifier which allows a method to accept a variable number of parameters.
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.
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' ) ) {
# ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With