[Catalyst] Re: using Plugin::Singleton and testing

Jonathan Rockway jon at jrock.us
Fri Nov 17 05:37:00 GMT 2006


On Thursday 16 November 2006 20:08, A. Pagaltzis wrote:
> A singleton is nothing but a global variable, except the
> identifier comes from the class namespace rather than the
> variable namespace. Put it in a global variable already.

Not entirely true.  Try this:

$global = "Oops, accidentally overwrote the instance with garbage.";

vs.

Singleton->get_instance() = "Oops, accidentally overwrote the instance.";

One will cause an error at some indeterminable time after the mistake, the 
other throws an error immediately, at the line where the mistake was made.  
Which do you prefer?

The point is, a Singleton isn't just a global variable, it's an encapsulated 
piece of data that your program can easily access anywhere.  Compare this 
code:

package Foo;
sub new { my $global = shift; bless {global => $global} => 'Foo' }
sub Bar { Bar->new($self->{global}) }
sub something { $self->{global}->something(...) }
package Bar;
sub new { my $global = shift; bless { global => $global} => 'Foo' }
sub Baz { Baz->new($self->{global}) }
sub another { $self->{global}->something(...) }
# etc.

to:

package Foo;
sub new { bless {} => 'Foo' }
sub Bar { Bar->new }
sub something { Global->instance->something }
package Bar;
sub new { bless {} => 'Foo' }
sub Baz { Baz->new }
sub another { Global->instance->something }
# etc.

In cases where many classes need the same data, a Singleton really helps 
simplify the code.  There are always coupling issues to worry about, of 
course (Singletons can be evil if you use them that way),  but there are some 
things that you can really only have one of.  The log file, the file 
descriptor "2" (STDERR), the database password, etc.

-- 
package JAPH;use Catalyst qw/-Debug/;($;=JAPH)->config(name => do {
$,.=reverse qw[Jonathan tsu rehton lre rekca Rockway][$_].[split //,
";$;"]->[$_].q; ;for 1..4;$,=~s;^.;;;$,});$;->setup;



More information about the Catalyst mailing list