Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Passing a variable recursively

by marinersk (Priest)
on Nov 06, 2012 at 07:36 UTC ( [id://1002424]=note: print w/replies, xml ) Need Help??


in reply to Passing a variable recursively

OO noob here, so I'm just asking without having tested this yet, but --

Wouldn't another approach be to pass the logger object to the module if you wish it to use that logger object instance?

something like:

# calling program stuff my $loggerHandle = new myLogger(); my $workerHandle = new myWorker(); my $returnValue = $workerHandle($loggerHandle, $Parameter, $Option, $E +tc);

You achieve the intended result, which is a lot like Global State, but not with a Global State implementation. You tell the subordinate method which logger to use, and its logging behavior is driven by its previously-established logging level attribute.

Or am I out in left field here, and worse, the game is soccer?

Replies are listed 'Best First'.
Re^2: Passing a variable recursively
by tobyink (Canon) on Nov 06, 2012 at 09:30 UTC

    Precisely. You should give functions and objects everything they'll need to perform their duties. Loggers, database handles, etc should be provided to objects as part of their constructor, or passed to each method/function call.

    The name for this general style of programming is "dependency injection" - you inject into an object/function everything it depends on. Generally speaking it is considered a good thing to do.

    That said, it is possible to go far with dependency injection. If a function needs to fetch something from the web, it's a good idea to allow people to "inject" an LWP::UserAgent or compatible object. But if a function needs to multiply two numbers together, then allowing people to inject their own implementation of integer multiplication as a coderef is a step too far. Generally common sense will tell you what dependencies should be injectable and what can be hard-coded.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1002424]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2024-04-23 09:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found