Hi...
Jochen Buennagel wrote:[color=blue]
> Singletons IMHO avoid the major drawbacks of global objects (which is
> the motivation for the pattern if I remember right). They initialize
> themselves when first used and they can't be deleted or overwritten by
> accident.[/color]
Well I wouldn't go so far as to say they are the end of the world, and
they do solve the initialisation problem. I even have a couple in my
current main app (don't tell anybody). The trouble is that they can get
damaged by any part of the code. Also if you ship some with a library,
because of the global scope they can affect any part of that library.
This makes understanding things just a little bit harder. It's little
bit less encapsulation.
[color=blue]
> That depends on the design of your classes and your tests. I usually use
> a Factory Method in the client object to get the singleton instance. For
> testing I swap that Factory Method out against one that returns a mock
> of the Singleton. (I use your Partial Mocks for that.)[/color]
A factory is almost always a superior approach. This is not so much a
singleton though, as you have to get access to the holding class to call
the factory method and, as you say, that can be mocked or switched by
subclassing. I am not against a cached instance. That is just normal
coding. It's the static global access and single instance in combination.
Actually I am going off of static methods as well, but that's another
story :).
[color=blue]
>
> Having Singletons carry data that changes after initialization to
> reflect the state of the application is indeed problematic, because it
> leeds to temporal coupling, which is near impossible to test well. I use
> Singletons mainly for "stateless" things that don't change after
> initialization. A database connection is a prime example.[/color]
That is a common one; PEAR uses it for example. In my current main job
(Wordtracker) we have one for the SessionPool (for PHP $_SESSION handler
access) and a Registry class (not surprisingly). That is just under 1%
of the total number of classes. When I see half a dozen in an
application I see it as a symptom of possible problems.
One that has caused me particular problems in the past is some kind of
Singleton "Auth" class. It often means you have to log in just to run
your tests. Given that such a class exists pretty near the top of the
application hierarchy (unlike a database connection) there really is no
excuse for not passing the object as a parameter.
[color=blue]
>
> Jochen[/color]
yours, Marcus
p.s. I'll try to do some PHP::Duploc work this holiday. Not finding much
time right now.
--
Marcus Baker,
marcus@lastcraft.com,
nokia@appo.demon.co.uk