Are singletons necessary ever? Is not simply keeping track of instantiation enough? - singleton

It seems to me that singletons enforce a single instance but why would an application that understands that there should be only on such instance even attempt to instantiate a second instance?

I think its also about managing the single shared instance. Synchronization to be precise.You don't want someone to use the resource when you are using it.
Private constructor and static method simply enforces the application to do so.
A lot of developers refrain from using it since its also difficult to test and causes multi-threading issues.

Related

Login as Singleton class

I have a direct question: Is a good pratice use Singleton pattern to control a class responsable for Login tasks, or another pattern is more appropriated? Or do not exist a patter to do this kind os issue?
Thanks.
Few people use singletons these days as they are almost becoming anti-patterns. I would recommend to learn Dependency Injection (DI).
With DI you can register the object you wish to use as singleton with a container and that container will serve or give that object to all other objects that need it. Of course you can register the object as a singleton - but not the usual singleton - and the container will guarantee that all objects which need it will receive the same instance.
Nevertheless, if you are building a small application then It would be better to use the Singleton pattern and avoid DI.
Jon Skeet has a very nice article about Singleton pattern or if you are using Java then you could use Enumerations to implement it, look implementations techniques on Google.
The singleton pattern is used when you have to prevent the creation of more than one instance of the same class. I do not really see the situation in which a login class should only have one instance so i would say using this pattern for a login class is overkill.
Then again, introducing a DI framework when you only need a simple singleton... now thats overkill :)
Yes and no. There's no 'best' or 'worse' practise.
Just do it, if using a singleton makes it easier to test and if the approach will get you to the pub earlier than learning and implementing DI just for the purposes of login.

Creating objects with the same arguments across the system

I have an object that performs a very specific task. To be created, this object needs some parameters. I create a new instance in some parts of my system. But there is the problem. What if a parameter or argument must be changed in the future? I will need to change it everywhere. Then I thought: "Well, maybe I can encapsulate its creation in a class, if some argument changes, I will need to change it just in a single place!".
It does make perfect sense to me. The real question is, is this "wrapper" object a factory? Its responsibility would be "Create a new object with specific parameters and return it". Consumers would just use this object ...
You a refactoring code to avoid duplication, that is itself likely to improve your overall maintainability.
If this piece of refactored code is creating objects then, yes, it is a factory. It really doesn't matter what you call it - is your code better structured now you have it? Then do it!
However, given that it is a factory study the classic design patterns concerning factories and understand what leads people to use more sophisticate forms of this pattern. Decide whether you have any of the forces that lead them to use "clever" factories.
The problem you describe is that all clients of your class have to change when the constructor parameters of that class change. Introducing a factory could help prevent recompilation of the clients. But does this really solve the problem? If you modify the class to be constructed with another parameter that parameter has to be determined somewhere, probably in the context of the clients that initiate the construction. How should the factory class know? Would the clients have to pass any context information to the factory?
What parameters are needed to construct the object? Do the clients provide them or could the objects be created beforehand and then injected into the clients as you would inject the factory (as I understand your question the latter seems to be the case)? Consider using a DI framework. This oftentimes makes factories obsolete.
Why are you afraid that your class is likely to be changed? Could it be that your class just does too much? Mind the Single Responsibility Principle. In your case also the Open/Closed Principle is an interesting study.
As I understand a factory does not necessarily address the problem you describe. Factories take the responsibility of creating objects away from clients so the client doesn't have to know the concrete type of the object. Just preventing that signatures remain stable can also be done by wrapping parameters in a single object. This is also a well known refactoring pattern. But it also doesn't solve the question where the new parameters come from.

Alternatives to Singleton when global access is wanted

I have spent the last couple of hours reading about the singleton pattern and why not to use it, amongst others those really good sites:
Singleton I love you, but you're bringing me down
How to Think About the "new" Operator with Respect to Unit Testing
Where have all the Singletons Gone?
I guess quite a lot of you know these already.
Looking at my code after reading that, I clearly am one of the maybe 95% of programmers that misunderstood and misused the singleton pattern.
For some cases, I can clearly remove the pattern, but there are cases where I am unsure what to do:
I know singletons for logging are accepted, one reason for that being that information only flows into them but not back into the application (just into the log file or console etc of course).
What about other classes which do not meet that criteria but are required by a lot of classes?
For example, I have a settings object which is required by a lot of classes. By a lot, I mean more than 200.
I have read into some other SO questions like "Singletons: good design or a crutch?", and all of them pointed out why using singletons is discouraged.
I understand the reasons for that, but I still have one major question:
How do I design a class which needs a single instance, accessible from everywhere, if not using the Singleton pattern?
The options I can think of would be:
Use a static class instead (though I don't see how this would be any better, looking at OOP and unit testing).
Have it created in an ApplicationFactory and perform dependency injection on every single class that needs it (keep in mind it's 200+ for some cases).
Use a singleton anyway, as the global access bonus outweighs the disadvantages for that case.
Something completely different.
It will depend on exactly what you mean by a settings object.
Do all 200 classes need all the settings; if not why do they have access to the unused settings?
Where do the settings come from and is there a good reason why each class can't load its settings as and when required?
Most importantly though, don't make changes to working code just because the code uses a pattern which is frowned upon. I've only used the singleton pattern once but I'd use it again.
EDIT:
I don't know your constraints but I wouldn't worry about multiple access from a file until it had been shown to be an issue. I would split up the configuration into different files for different classes/ groups of classes or, preferably, use a DB instead of files with different tables providing data for each class.
As an aside I've noticed that once you put the data in a db people seem to stop worrying about accessing it multiple times even though you're still going to the file system in the end.
PS: If other options aren't suitable I'd use a singleton... you want data to be globally available, you're not willing to use dependency injection, you only want the file to be read once; you've limited your options and a singleton isn't that bad.
Isn't this already discussed extensively and exhaustingly?
There is no misuse of the pattern. If your software works as expected (inlcuding maintainability and testablility) you are right with singletons.
The thing about people complain is that the singleton pattern has more impact than only restrict a class to have a single instance.
you introduce a global variable
you cannot build a subclass
you cannot reset the instance
If all this is not a problem for you: Use singletons all over the place. The pattern discussion is academic and hairsplitting.
And - to answer your question - checkout the monostate vs singleton thread: Monostate vs. Singleton

How to pass global values around (singleton vs. ???)

I've inherited a project that stores various parameters either in a config file, the registry and a database. Whoever needs one of these parameters just reads (and in some cases writes) it directly from the store. This, or course, is stupid, so my first thought was to refactor the existing code so that the client doesn't know where the parameter is stored in. I created a classic AppSettings class that has a property for each parameter. Since the store has to have global scope I made a thread-safe singleton. The class doesn't store the parameter values in fields but rather acts as an access point by reading and writing them to and from the actual store, be it config file, registry or database. These days it's hard to avoid all the talk about the dangers of singletons and global state. I will take a proper look at dependency injection and Spring etc later, but for now, I just have a couple of questions.
What type of problems, other than testability, can you see with my solution?
What would be a light weight alternative? Creating a factory for each object that uses the parameters is not an option (too much work).
Wouldn't using a singleton serve as an acceptable compromise until I have a chance to do some heavier refactoring?
If the properties in my singleton class only had getters, would that make it OK?
I can anticipate that the store for some of the parameters will change in the future (eg. from registry to database), so that was my motivation for hiding the store behind a singleton class.
This is a bit of a non-answer, but I highly recommend the c2wiki's pages on Singletons as a reference http://c2.com/cgi/wiki?search=Singleton
And also the page http://c2.com/cgi/wiki?GlobalVariablesAreBad
I think the general verdict is that global state creates coupling between vastly different parts of your system that must be thought about and designed around very carefully. The question is, are all of those settings truly global and needed by disparate parts of the system? If not, then is there any way to separate them into smaller parts that can live inside different modules at a lower access level?
If it's a small project I wouldn't worry too much about it, but there is a lot of wisdom on those c2wiki pages about global state and singletons being a pain for larger projects.
I would challenge the assumption that since the config data is global, that you need a global singleton to access it, especially for reading. Consider creating an AppSettings class that can be invoked as needed to read your config settings.
If you need to write in a thread-safe manner, you can create a static (or singleton) private member of the AppSettings class to control writing only. Thus any instance of AppSettings can write, but the "global" access is actually restricted to the AppSettings class.
Thanks, guys. I would consider this a medium-size project (about 200KLOC) and it's C#. The problem is that the project has a long and troubled history and a lot coders have worked on it. As much as I'd like to properly learn dependency injection (as I do understand and subscribe to the concept), the deadline is closing fast so now is not the time for it. After looking at my current singleton class I decided to split it into two instance classes. Some of the parameters are used all over but some only in a single assembly. And like Doug said, I can achieve thread-safety just as easily with an instance class.
As for the various dependency injection frameworks, the problem is there are too many. I've briefly looked at Spring and Unity. I wish I could find a summary of the differences.
Thanks again!

what happens if more than one thread tries to access singleton object

Not during instantiation, but once instantiation of singleton object is done, what will happen if two or more threads are trying to access the same singleton object? Especially in the case where the singleton object takes lot of time to process the request (say 1 min)... In this case, if for ex., 5 threads try to access the same singleton object, what will the result be?
Additional question: normally when should we go for the singleton pattern and when should we avoid it?
Unless synchronization (locking) is being performed within the Singleton, the answer is this: it's a free-for-all.
Though the Singleton ensures that only one instance of an object is used when requested, the pattern itself doesn't inherently provide any form of thread safety. This is left up to the implementer.
In the specific case you cited (with a long running method), it would be critical to synchronize access to any method that uses class or object-level variables. Failure to do so would, in all likelihood, lead to race conditions.
Good luck!
The general rule of thumb i use for Singletons is that it should not affect the running code, and have no side-effects. Essentially for me, in my projects this translates into some kind of logging functionality, or static value lookup (ie. loading some common data from a database once and storing it for reference so it doesn't have to be read in everytime its needed).
A singleton is no different than any other object other than there is only one instance. What happens when you try to access it will largely depend on what the accessing threads are attempting (ie read vs write) and what kind of data your singleton is holding.
The answer to your question as it is, is "it really depends". What kind of singleton? i.e. what does it do, and how does it do it? And in what language?
The reality is that the singleton patter)n only dictates and enforces that you can only have one instance of a certain object. In of itself it does not say anything about multiple threads accessing that object.
So, if coded right (with thread synchronization implemented correctly) there is no reason why it shouldn't behave correctly - even if the requests to the object take a really long time to process!
Then you need thread safe implementation of singleton pattern.
Find this article useful for the same which describes most of the multi-threading scenario of singleton pattern.
HTH!