Are singletones really that bad?

Possible duplicate:
What's wrong with singleton?

It is clear that many design templates can be abused in some cases, and, as always, mom always said: “Too much good is not always good!”

I notice that these days I use Singletones a lot, and I'm worried that I can abuse the design template myself, and get deeper and deeper into the habit of bad practice.

We are developing a Flex application that has a rather large hierarchical data structure stored in memory when the user is working on it. The user can download, save, modify and update data upon request.

This data is centralized using the Singleton class, which combines several ArrayCollections, Arrays, value, and some other native member variables opened through getters and seters.

To get a link to our data from anywhere in the application, we make the whole method of the Model.getInstance () method, and I'm sure everyone is familiar. This ensures that we always get the same copy of the data, since during the design we said that only one instance is allowed to exist during the life of the application.

From this centralized data warehouse it is easy for us, for example, to cancel the properties of changed events and may have several user interface components that reference the central data, update their displays to reflect the data changes that have occurred.

Until now, this approach has been effective and has proven to be very practical for our circumstances.

However, I am in the fact that when creating new classes I exaggerate a little. Questions such as a class should be Singleton, or if it is rather managed in some other way, for example, for example, using a factory, for example, sometimes it becomes a bit complicated, with some uncertainty.

Where do I draw a line with single dots? Is there any good guidance for deciding when to use singletones and when to stay away from them.

Also, can anyone recommend a good book on design patterns?

+47
design-patterns singleton
Jun 19 '09 at 22:26
source share
12 answers

The main thing to remember is that design patterns are just a tool to help you understand abstract concepts. Once you understand this, limiting yourself to a “recipe” from a book is pointless and impairs your ability to write code that is most suitable for your purpose.

However, reading books such as GoF will provide you with more ways to think about problems, so when it comes time to implement something on your own, you will have a wider range of perspectives for solving the problem.

In your case, if using singleton makes sense in every case, then go straight ahead. If this "variety" is suitable, and you have to implement it in some awkward way, then you need to come up with a new solution. Forcing a pattern that is not perfect is somewhat reminiscent of clogging a square pin in a round hole.

Given that you say: “This approach was effective and very practical for our circumstances,” I think you're all right.

Here are some good books:

Book "Gang of Four" - a classic book for design templates

Head First Design Patterns - I heard that this is recommended by several people as an alternative

+35
Jun 19 '09 at 22:29
source share

Yes, singletons are bad. They are bad because everything they do for you combines two properties, each of which is bad in about 95% of cases. (Which would mean that on average single numbers are bad 99.75% of the time;))

The syntax defined by GoF is a data structure that:

  • Provides global access to the object and
  • Ensures that only one instance of an object can ever exist.

The first is usually considered bad. We do not like globals. The second is a little more subtle, but as a rule, there are practically no cases where this is a reasonable restriction to ensure compliance.

Sometimes, it makes sense to have only one instance of an object. In this case, you decide to create only one. You do not need a singleton to enforce it.

And, as a rule, even when it “makes sense” to have only one instance, in the end, it makes no sense. Sooner or later you will need more than one registrar. Or more than one database. Or you will need to recreate resources for each of your unit tests, which means that we must be able to create them as we see fit. Prematurely removing the flexibility of our code before we understand the consequences.

Singlets hide dependencies and increase communication (each class can potentially depend on a singleton, which means that the class cannot be reused in other projects unless we reuse all of our singleton), and since these dependencies are not immediately visible (as a function / constructor), we don’t notice them and usually don’t think about it when we create them. It’s so simple to just pull in a singleton, it acts almost like a local variable and that’s it, so we tend to use a lot of them as soon as they are there. And that makes them almost impossible to remove again. You end up, maybe not with spaghetti code, but with spaghetti dependency graphs. And sooner or later, your runaway dependencies will mean that single games start depending on each other, and then you get circular dependencies when you try to initialize.

They make it extremely difficult for unit testing. (How do you test a function that calls functions on a singleton object? We don’t want the actual singleton code to execute, but how to prevent this?

Yes, singletons are bad.

Sometimes you really need a global one. Then use global, not single-line.

Sometimes, very very rarely, a situation may arise when creating multiple instances of a class is an error, where it is impossible to do without causing errors. (The only case I can think of, and even this is far-fetched, is if you imagine some kind of hardware device. You only have one GPU, so if you are going to match it with an object in your code, it makes sense that only one instance can exist). But if you find yourself in such a situation (and again, for emphasis, a situation where several instances cause serious errors, and not just a situation where “I can’t think of any use cases for more than one instance”), then apply this is a limitation, but do it without making the object globally visible.

Each of these two properties can be useful, in rare cases. But I can not think of a single case where a combination of them would be good.

Unfortunately, many people have the idea that "singletones are globally compatible with OOP." No, they are not. They still experience the same problems as global ones, in addition to introducing some others that are completely unrelated. There is absolutely no reason to prefer a singleton over a plain old global one.

+106
Jun 19 '09 at 22:55
source share

Software developers seem to be fairly evenly divided into two camps, depending on whether they prefer an idealistic coding style or a pragmatic one:

  • Idealistic: never use a singleton pattern.
  • Pragmatic: Avoid the singleton pattern.

Personally, I advocate a pragmatic approach. Sometimes it makes sense to break the rules, but only if you really understand what you are doing and are ready to accept the associated risks. If you can answer yes to the questions below regarding your specific use case, a singleton template can provide some practical benefits.

  • Is singleton external to your application? Databases, queue services, and ESBs are all legitimate examples of singleton pattern macros.
  • KISS: is your entire application limited to 2-3 internal singles?
  • DRY: Are these singletones inherently global and should therefore drop links to almost every object in your application? (e.g. registrar or component broker)?
  • Do your singles affect each other and / or the operating environment?
  • Have you provided the right start and shutdown sequences for each singleton, including memory management considerations? For example, the Grand Central thread pool may need the Run () and Shutdown () instance methods in main () to ensure that tasks are completed only when the objects in which they are running are in an acceptable state.
+14
Mar 24 '11 at 20:53
source share

Singlets do not kill programs; programmers kill programs.

Like any programming construct, with proper use you will not shoot in the foot.

Recommended books are good, but they do not always provide enough background that comes with experience when you can choose to use Singleton.

This experience only arises when you find that Singleton is a bad choice when you need to have multiple instances, and suddenly you have a lot of problems with naming objects around the world.

Sometimes it’s better to go ahead and have references to objects, but the fact that you are using Singleton really helps to determine the scale of the problem you are facing if you had to reorganize it to a different design. I think this is a very good thing: that is, just having a class in general (even if it is poorly designed) gives you some ability to see the effects of class changes.

+9
Jun 19 '09 at 22:42
source share

We started a project in which we basically come across the same question, that is, how to access the model and especially its root element. A project is not a Flex application, but a game! web application, but it does not matter.

The presence of a unique unique object in the system is in order, the problem is how to access it . Thus, the debate about singleton is related to the concept of dependency inversion (DI) and how to get objects.

The main arguments for DI are the following:

  • verifiability and ridicule
  • disconnecting an object from use (which may lead to life cycle management)
  • separation of problems

Possible approaches to DI (see classic article by Fowler):

  • pass an object in the method parameters
  • service locator
  • DI structure

In this perspective, a singleton template is just a kind of service locator, for example. Model.getInstance() .

But to provide maximum flexibility before future changes, a reference to a unique object should be transferred as much as possible and obtained using Model.getInstance() only if necessary. It will also give cleaner code.

+4
Oct. 14 2018-10-10
source share

In my opinion, the use of singletones directly signals a design flaw. The reason is that they allow you to bypass the mechanisms for creating and destroying ordinary objects built into C ++. If an object needs a link to another object, it must either pass a link to it during construction, or create a new instance inside it. But when you use singleton, you are clearly confusing the creation and breaking cycle. A related problem is that it is extremely difficult to control the lifetime of a singleton. As a result, many packages that include common singleton implementations also include clumsy object life managers, etc. Sometimes I wonder if they exist simply to control single player games.

Basically, if you need to use an object in many places, it must be explicitly created at the highest common point on the stack, and then passed through the link to everyone who uses it. Sometimes people use Singletons because they have problems passing multiple arguments to new threads, but don’t get into it, explicitly define your stream arguments and pass them to the new thread in the same way. You will find that your program is much cleaner and there are no unpleasant surprises due to static initialization dependencies or erroneous deletion.

+3
Aug 14 '10 at 0:20
source share

The singletones are, of course, not bad. They have their own application, some of them are very good. Singletones tend to be abused by inexperienced developers, as this is often the first design they recognize, and it's pretty simple, so they push it around the place without thinking about the consequences.

Every time you want to use singleton, try to consider why you are doing this and what are the advantages and disadvantages of using this template.

The singleton really does create a globally accessible set of “material” (data or methods), and I think most people would agree that using too many global variables is not a great idea. The whole purpose of classes and object orientation is to group things into separate areas, and not just throw everything into one global global space.

One of the “patterns” that I find, I prefer more than loners, is to convey the necessary items from above. I create them once during the initialization phase of my applications and pass them to all objects that need access to them. It imitates part of a one-time creation of a singleton pattern, but without the "global" part.

The whole point of a singleton is that it is for objects where only one must exist. You mentioned a set of data management classes. Perhaps you think that there are actually cases where an application might want to create 2 sets of data management classes, so perhaps using a singleton on this is not entirely correct. Instead, if you created these data classes in an init application and passed them, you would only create 1 set, as that is what you need in the current application, but you leave open the possibility that at some point, if you need the second set you can easily create them. Also, if the data management classes are indeed accessible globally from anywhere in the application. I think not, instead they should only be accessible from a lower level access level.

Some people have recommended the GOF book. I would say yes, this is a great book, but first try to find a book about general architecture first, first read about 2/3 / n-level design, encapsulation, abstraction and these principles. This will give you a more solid foundation for understanding the proper use of the patterns that GOF talks about.

[Edit: another time when a singleton option might be useful is when you want one access point to be something, but the implementation detail can be more than one. The caller does not need to know that under the covers their request for a singleton object is actually resolved against several available objects, and one is returned. I’m thinking of something like a thread pool here where the use goes, hey, just give me the thread, I need 1, but I don’t care which one]

+2
Jun 19 '09 at 22:51
source share

I know this is an old thread, but no one seems to have mentioned the actual template that matches what the OP was trying to do. I believe that he describes the need, called "Mediator . " SourceMaking is a fantastic site for learning / linking to this kind of information. Definitely, I'm going to post people to develop programs. In addition, it is generally a good idea not to buy in the notion that any design template is necessarily inherently good or evil. They all use, they only learn when and where to use them, which is a trick. People who claim to never use Singleton do not understand their usefulness.

+2
May 11 '12 at 15:17
source share

No, they are not necessarily bad.

As for the book, you need to start with the classics .

0
Jun. 19 '09 at 22:27
source share

Singletones are not "so bad." If you have a lot of connected singletones, and you can replace / combine several of them with Factory, without losing anything you care about when you do it.

As for books, well, here's some kind of canon .

0
Jun 19 '09 at 10:30
source share

I thought the singleton were good .

0
Jun 19 '09 at 22:32
source share

Google seems convinced that the Singletons are a bad idea.

Not to assume that everything Google does is perfect, or that their every opinion is the end of any argument, but they went so far as to write this Singleton detector to root them out. Make up your mind.

0
Jun 20 '09 at 1:09
source share



All Articles