3

I previously used Singletons for global classes, if it's absolutely necessary i.e. logging, error handling. But I am now using unit testing which doesn't like these!

I would like to ask a basic question on globals. What's the point in them? What's wrong with creating a new instance of a class when you need it?

razlebe
  • 7,134
  • 6
  • 42
  • 57
Christopher Grigg
  • 2,238
  • 27
  • 33
  • 1
    "I would like to ask a basic question on globals. What's the point in them? What's wrong with creating a new instance of a class when you need it?" I think I don't understand your question. There is nothing wrong with creating a new instance of a class when you need it... – iuiz Feb 03 '11 at 12:50
  • Let me try to clarify by giving an example: With an application that uses logging in every single class, is it not a bad idea to instantiate the log class every time, as opposed to using a singleton which accesses the same instance of the logging class? Presumably this will use more memory? I feel like I have some knowledge but am missing the basics! @iuiz – Christopher Grigg Feb 03 '11 at 14:20

2 Answers2

4

you should read this SO thread: What is so bad about Singletons?

personally, i'm all for singletons for things like logging, undo/redo stacks, localization and notifications from one display list branch to another - when event bubbling isn't really an option.

while they're not always ideal, singletons certainly have their place and can make development a lot easier, regardless of what some purists might say.

Community
  • 1
  • 1
Chunky Chunk
  • 16,553
  • 15
  • 84
  • 162
3

It is true, sometimes singletons can create problems, that you won't have without them.

I try to give you a list of my thoughts on this matter:

  • The most severe would be, that your software has circular dependencies. If you are working on a SOA architecture it can happen quite fast, if you are not careful.

  • Also singletons can often lead to very close coupling of your classes, which makes you job as a tester really really hard.

  • If you work on a big project and the way another class can get an instance of your Singleton changes, you will have to change lots of code. This can also happen without singletons, but I have the feeling, that it happens more often with singletons.

But sometimes a singleton is a nice idea and you should stick to it. Even in AS3 you can use singletons with the famous private class argument constructor workaround. As a heuristic when not to use singletons, i would suggest thinking about, if the class needs lots of references to other singletons. And with some thinking you can also make your singletons testable.

iuiz
  • 957
  • 1
  • 10
  • 23