Login as Singleton class - authentication

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.

Related

When is it appropriate to use #Singleton and #Prototype in Micronauts?

I read so many bad things about singleton pattern (What is so bad about singletons?), however, #Singleton is used everywhere in this Micronaut doc to illustrate inversion of control https://docs.micronaut.io/1.3.0.M2/guide/index.html#ioc
When is it appropriate to use #Singleton? For example, if I have a UserInfoService that has getUserInfo, createUserInfo, updateUserInfo method, is it a good idea to use #Singleton?
Another separate question is when do I use #Prototype, because if I don't use any annotation for a function/class, isn't it by default a prototype (as in I initiate a new instance of it in another class/function)?
When is it appropriate to use #Singleton? For example, if I have a
UserInfoService that has getUserInfo, createUserInfo, updateUserInfo
method, is it a good idea to use #Singleton?
UserInfoService should almost certainly be a stateless singleton.
Another separate question is when do I use #Prototype, because if I
don't use any annotation for a function/class, isn't it by default a
prototype (as in I initiate a new instance of it in another
class/function)?
If you initiate a new instance, then the annotation doesn't matter. The annotation only affects instances that the Micronaut container creates for you. For #Singleton the container creates a single instance and injects the same instance at all injection points that require it. For #Prototype the container creates a new instance for each injection point.
All of this is about application design more than it is about Micronaut. Micronaut provides a simple mechanism for you to declaratively express (by way of #Singleton or #Prototype) whether or not you want the same instance to be shared or not but the issue is really about application design. In general you should prefer stateless singletons. If for some reason you have a bean that must be stateful and you have good reasons to not want to share instances from different contexts, then #Prototype might be appropriate.
I hope that helps.
Let's be 100% clear that the GoF Singleton design pattern and the #Singleton annotation are two different things.
Consider that the Singleton design pattern requires you to change your code. You must write the code in such a way as to prevent multiple instantiations.
On the other hand, you can add the #Singleton annotation to any class you like, without modifying its code to prevent instantiation; and as #Jeff-Scott-Brown points out, you can instantiate this Micronaut "Singleton" repeatedly by simply calling its constructor.
The #Singleton annotation does not exhibit those negative consequences you've read about in the Singleton design pattern, because it doesn't implement the Singleton design pattern. The term is overloaded to mean two different things here.
On a related note the #Prototype annotation doesn't follow the GoF Prototype design pattern either. Spring prototype following prototype design pattern
As Jeff Scott Brown covers most parts of your question, your have to be careful to the nuance between Singleton scope in Spring and singleton pattern.
Some of the main differences between these 2 are
Singleton pattern ensures one instance of a particular class of per
class loader.
Spring Singleton is “per container per bean”.
Hope that helps.

Should a class named `User` be an implementation of Singleton Pattern?

Today I read a lot of articles about how Singleton Pattern is bad, such as
violating single responsibility principle
inability to subclass
inability to use abstract or interface classes
High coupling across the application
make unit test difficult
And then I remember I have a program with a class named User which has field userName and password and something else related to User. In my conceive the program should only have one user instance, which is created when a human logins in my program. Based on this, should I insist design User class as Singleton Pattern, or is there any good design conceive I should use?
Additionl:
Another doubt. Using Singleton Pattern, I can get the only instance myUser everywhere. If I should not go with Singletion Pattern, How should I get the only instance myUser?
You might want to look at dependency injection. These days there exist many frameworks to assist you with wiring of the dependency injections so that you can specify in the framework that you expect a certain object to behave like a singleton. In other words if another object also requires the same "singleton" object, the framework should not create a new instance, but "inject" the already existing instance.
If you develop in Java, you may for example look at the way Guice did it: https://github.com/google/guice/wiki/Scopes They allow you to specify whether you want to create an "eager singletons" (created even if not needed yet) or "lazy singletons" (created on the fly only when required). Even if you are not using Java other programming languages got similar concepts that you could look out for.
What I would suggest is that you make the "User" object not a singleton and "inject" your "User" object into the classes that requires the "User" object. If possible, let the dependency injection framework of your choice handle the wiring so that you do not accidentally create more than one instance.
This way you will still be able to achieve most of the above mentioned advantages you posted in your question and still enjoy the benefits of a "singleton".
It depends on your context. If your application must have one and only one User, then use Singleton pattern. Your 5 points mentioned will be completely counter-productive.
In your example, this is not the case. But just one and only one instance is mandatory for the execution of one process. You should take in account #Koning response then.
For example, Spring security implements some common patterns of user logged with static methods :
SecurityContextHolder.getContext(). getAuthentication()
If you look at Microsoft memberhship than you will see that they store all data on session level. The best way I see to implement such logic which will be stored on all session level is Singleton pattern, because you won't need two classes working with user data. As alternative you can use static classes, but you couldn't serialize your user data in this case

Should every Facade be implemented as Singleton?

In descriptions of Facade and Singleton you can read : "Facade is often implemented as singleton".
I'd like to know when should I implement Facade as singleton and when it is a bad idea.
No. It is usually implemented because easier to call, but it gives several disadvantages (added from this answer):
Code coupling
Not-concurrent safe by default
Not Testable
One of the good (bad) point from the link is, it carry the lifetime of the entire application, so it never get disposed. Which can be bad if not control-able from the caller.
Applied especially for framework components.

Object Oriented Programming principles

I was wondering, I recently read an article that spoke of the ills of using the singleton pattern siting the disadvantage of global variable occurrence and rightly that the singleton violates alot of the rules we learn from OOP school, single responsibility principle, programming to interfaces and abstract classes and not to concrete classes... all that good stuff. I was wondering how then do you work with like database connection class where you want just one connection to your DB and one object of your DB floating around. The author spoke of Dependency Injection principle which to my mind stands well with the Dependency Inversion rule. How do I know and control what object gets passed around as a dependency other than the fact that I created the class and expect everyone using it play nice and make sure they are using the right resource?!
Edit: This answer assumes you are using a dependency injection container, either one you wrote yourself, or one you got from a library. If not, then use a DI container :)
How do I know and control what object gets passed around as a dependency other than the fact that I created the class and expect everyone using it play nice and make sure they are using the right resource?!
By contract
The oral contract - You write a design spec that says "thou shalt not instantiate this class directly" and "thou shalt not pass around any object you got from the dependency injection container. Pass the container if you have to".
The compiler contract - You give them a dependency injection container, and they grab the instance out of it, by abstract interface. If you want only a single instance to be used, you can supply them a named instance, which they extract with both the name, and the interface.
ISomething instance = serviceLocator.ResolveInstance<ISomething>(
"TheInstanceImSupposedToUse");
You can also make all your concrete classes private/internal/what-have-you, and only provide them an abstract interface to operate against. This will prevent them from instantiating the classes themselves.
// This can only be instantiated by you, but can be used by them via ISomething
private class ConcreteSomething : ISomething
{
// ...
}
By code review
You make group-wide coding and design standards that are fair, and make sure they are understood by everyone within the group.
You use a source control mechanism, and require code reviews before they check in. You read over their code for what they link to, what headers they include, what objects they instantiate, and what instances they are passing around.
If they violate your rules during code reviews, you don't let them check in until they fix their code. Optionally, for repeat offenders, you make them pay you a dollar, you make them buy you lunch, or you hire a different contractor to replace them. Whatever works well within your group :)
For those who criticize the singleton pattern, based on SRP, here is an opposing view. Also, I've found that dependency injection containers can create as many problems as they solve. That said, I'm using a promising compromise, as covered in another post.
Dependency injection containers (even one you develop yourself, which isn't an entirely uncommon practice) are generally very configurable. What you'd do in that scenario is configure it such that any request for the interface that implementation, well, implements would be satisfied with that implementation. Even if it's a singleton.
For example, take a look at the Logger singleton being used here: http://www.pnpguidance.net/News/StructureMapTutorialDependencyInjectionIoCNET.aspx
Don't take what you read anywhere as absolute truth. Read it, understand it and then you can see when it's best to apply certain things. In your case, why wouldn't you want to create a static singleton?

IOC containers and IDisposable

It was recommended to me that, when using an IOC container, I should change this:
class Foobar: IFoobar, IDisposable {};
Into this:
interface IFoobar: IDisposable{};
class Foobar : IFoobar{};
I'm wondering if this is ok, or if it solves one problem and creates another. It certainly solves the problem where I badly want to do this:
using( IFoobar = myContainer.Resolve<IFoobar>() )
{ ... }
And now I know that any substitute won't cause a run-time error.
On the other hand, now all my mock objects must handle IDisposable too. Am I right that most any mocking framework handles this easily? If yes, then perhaps this is a non-issue.
Or is it? Is there another hidden gotcha I should watch for? It certainly occurs to me that if I were using an IOC container not for unit tests / mocking, but for true service independence, then this might be a problem because perhaps only one of my swappable services actually deals with unmanaged resources (and now I'm having to implement empty "IDispose" operations in these other services).
Even this latter issue I suppose I could live with, for the sake of gaining the ability to employ the "using" statement as I demoed above. But am I following a popular convention, or am I missing an entirely different and better solution?
Deriving an interface from IDisposable is in my opinion a design smell that indicates a Leaky Abstraction. As Nicholas Blumhardt put it:
an interface [...] generally shouldn't be disposable. There's no way for the one defining an interface to foresee all possible implementations of it - you can always come up with a disposable implementation of practically any interface.
Consider why you want to add IDisposable to your interface. It's probably because you have a particular implementation in mind. Hence, the implementation leaks into the abstraction.
An DI Container worth its salt should know when it creates an instance of a disposable type. When you subsequently ask the container to release an object graph, it should automatically dispose the disposable components (if their time is up according to their lifestyles).
I know that at least Castle Windsor and Autofac does this.
So in your case, you should keep your type like this:
class Foobar: IFoobar, IDisposable {};
You may find Nicholas Blumhardt's post The Relationship Zoo interesting as well - particularly the discussion about Owned<T>.