In general, what would make your program more maintainable?
I know a lot of folks that make heavy use of Singletons, but that seems like a cop-out, which creates a kind of global junk drawer organization.
In general, what would make your program more maintainable?
I know a lot of folks that make heavy use of Singletons, but that seems like a cop-out, which creates a kind of global junk drawer organization.
Judging from some SO threads, a lot of folks don't like Singletons, for good reasons. See
Chain of Responsibility sounds better in general, since it allows different handlers to each take its turn in dealing with the event, so it is a much more flexible approach.
Without more details, it is hard to give a more concrete answer.
It depends very much on the problem you are trying to solve.
If there is guaranteed one handler for a particular event that is built in stone, then a chain of responsibility may well be over engineering, and would massively over complicate the system. It could turn into a maintenance nightmare. A chain with only a single link in it is not much of a chain and singleton may be much better suited.
However, if the system needs to be more losely configured, with a handler for an event being more dependant on a particular context, then a singleton would be far too tightly coupled. If you find your self with code like :
if (event == "this")
do this
else if (event == "that")
do that
.. in your singleton, then chain of responsibility would probably be better.
Always choose the right tool for the right job!
And also dont be afraid to change approaches when needed. If the problem starts simple, start with Singleton. Things may never get any more complicated than that and everyones happy. If things get more complicated as time goes by, and you notice yourself putting loads of branches in your singleton code - it is time to adapt! Rip out the singleton and plug in the chain... or some other pattern if that seems more suitable.
The idea behind focusing on loosely coupled code is to made it easier to plug functionality in and out so a solution only needs to be there for as long as it is needed.
Singletons are a kind of global. They seem to wreak havoc upon the TDD model. This page is linked to on the AsUnit homepage: http://asserttrue.com/articles/2007/07/14/static-classes-singletons-and-the-observer-pattern
Instead of accessing a Singleton statically, opt to pass or store a reference to the needed object. The Inversion of Control and Composite patterns are helpful in place of Singletons.