Perl: the Markov chain saw | |
PerlMonks |
Re: Access to single object from multiple other objectsby tobyink (Canon) |
on Oct 31, 2013 at 08:56 UTC ( [id://1060542]=note: print w/replies, xml ) | Need Help?? |
Singletons and global variables are both manifestations of "global state". Generally speaking, global state is the enemy. (And I don't mean that as an anti-UN conspiracy theorist!) If the global state is mutable (i.e. different parts of the code can alter it), then it can result in spooky action at a distance. Even if it's immutable, it can result in too tight coupling between different bits of code. It's certainly best to pass into functions all the data they need to do their job, and pass to object constructors all the data the object needs. It can be cumbersome to pass around database handles from object to object, but there are patterns that can be followed to help eliminate some of these difficulties. For example, say you have a Document object that creates several Section objects, and needs to pass its database handle on to its sections. You might have something like this...
This can be transformed into:
This means that the dbh pass-the-parcel happens in just one place instead of many. It also makes it easier for subclasses of Document to override the construction of Section objects. (My module MooseX::ConstructInstance can help with implementing this pattern.)
use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name
In Section
Seekers of Perl Wisdom
|
|