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

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.

Related

Singleton toolbox vs factory method

Apparently, singletons are bad, and a factory method is recommended. I'm wondering if a singleton toolbox is any better than a singleton.
In my opinion, It's really weak to think that singletons are bad,factory methods are good.
Each of them has preferences. As consequence, I'm sure that there is misunderstanding here.
I know that wikipedia is not the best source. But check out the definition of them. The range of situations are not the same for these patterns.
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.
In class-based programming, the factory method pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the exact class of object that will be created. This is done by creating objects via calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

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.

When to use the abstract factory pattern?

I'm trying to succinctly describe when to use a factory, for both myself and my team. I ran across the following related questions, which helped somewhat:
When to use factory patterns?
(useful pdf link is broken)
How do you create your Factories?
(more 'how' rather than 'when')
What is your threshold to use factory instead of a constructor to create an object?
(some general answers)
Factory Pattern. When to use factory methods?
(more about factory methods than factory classes)
When to use Factory method pattern?
(again more about factory methods)
Based on these links, and a bunch of other sources (listed at the bottom), I've come up with the following:
When to use the abstract factory pattern:
when you use an interface var or the 'new' operator
e.g. User user = new ConcreteUserImpl();
and the code you are writing should be testable / extensible at some point
Explanation:
interfaces by their very nature imply multiple implementations (good for unit testing)
interface vars imply OCP- and LSP-compliant code (support sub-classing)
use of the 'new' operator breaks OCP/DI, because highly-coupled classes are hard to test or change
"Do I create a factory for every object type? That seems excessive."
no, you can have one (or a few) factories that produce a lot of (usually related) object types
e.g. appFactory.createUser(); appFactory.createCatalog(); etc.
When NOT to use a factory:
the new object is very simple and unlikely to be sub-classed
e.g. List list = new ArrayList();
the new object is not interesting to test
has no dependencies
performs no relevant or long-running work
e.g. Logger log = new SimpleLogger();
References:
http://googletesting.blogspot.com/2008/08/where-have-all-singletons-gone.html
http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/
http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/
http://en.wikipedia.org/wiki/Dependency_Injection
http://en.wikipedia.org/wiki/Open_Closed_Principle
http://en.wikipedia.org/wiki/Liskov_substitution_principle
My question is: is my summary accurate, and does it make sense? Is there anything I've overlooked?
Thanks in advance.
I'd also say don't use a factory when you have a particular implementation that you want. To continue the List example, I know that I want an ArrayList because I'm doing random access. I don't want to rely on a factory getting this right when I can do it myself.
Conversely, when I don't want to know about the concrete subclass then I can use a factory and let it worry about which object to actually instantiate.
I guess I'd suggest that you add a bullet to the "when to use the abstract factory pattern" that says "and you don't really care which concrete subclass you get", and the converse to "when not to use a factory".
EDIT: Be careful to avoid the general-purpose tool-building factory factory factory.
In general, use it when you want to be able to switch of implementation by external configuration.
JDBC and JAXP are excellent examples. For more examples, check this answer.
Abstract Factory pattern provides with a way to encapsulate concrete factories that share some commonality with each other, meaning they implement same interface/abstract class.
You need to use factory pattern whenever you want to control the initialization of your objects, instead of giving the control to the consumer.

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>.