Singletons or non-singletons wrapped by a Singleton - java

I have a singleton class called SingletonController1.
This SingletonController1 instantiates a bunch of others Singleton classes.
SingletonController1{
Authenticator - Singleton;
DBAccessor - Singleton;
RiskAccessor - Singleton;
}
My question is, what if I rework this design to:
SingletonController2{
Authenticator -non-singleton;
DBAccessor -non-singleton;
RiskAccessor -non-singleton;
}
As long as SingletonController2 is the only class that instantiates those three non-Singleton classes, wouldn't this be functionally the same as the previous design?
Cheers

Functionality will be the same, but flexibility much greater in the second case as the non-singleton classes can be reused elsewhere in your application/system. If they don't need to be singletons let they not be singletons.

Yes. These 2 designs accomplish the same thing, given your condition that no class other than Singleton2 instantiates Authenticator, DBAccessor and RiskAccessor.

I think you are on the right track, but push it further. Go right back to your root of your program and you only need one singleton. There's a logical step after that too.

Lately, what I've been doing is using dependency injection frameworks for the creation of objects. What they can do is make a class into a singleton with a line of code that configures how that class is created. That way if you ever need more than one of an object, you just delete the line and change the architecture for calling it slightly. I've just used a framework built to work with Unity 3D, so I don't know for certain if the frameworks outside of Unity 3D support this, but I have a good feeling they do.

Related

Dagger 2 and use of #Singleton

I have inherited a Java web service project that is using Dagger 2. Based on my so far limited understanding of Dagger I am confused as to why every single class that is injected has the singleton annotation on it in the dagger module class's. If I was creating this application without dagger they would not all be singletons, is this something specific to dagger or have the previous developers simply misused Dagger?
[...] every single class that is injected has the singleton annotation [...] is this something specific to dagger [...]?
Nope. #Singleton is the only scope included with Dagger by default, but you can also create custom scopes, use #Reusable which may create multiple objects but will reuse them if possible, or no scope at all.
or have the previous developers simply misused Dagger?
If possible you should just ask them. If every object is a Singleton this looks like they did not invest a lot of thought in the setup and just copy-pasted declarations, at least this would be my assumption.
From the section about Reusable in the user guide:
Sometimes you want to limit the number of times an #Inject-constructed
class is instantiated or a #Provides method is called, but you don’t
need to guarantee that the exact same instance is used during the
lifetime of any particular component or subcomponent. This can be
useful in environments such as Android, where allocations can be
expensive.
Two main differences:
#Singleton annotated class is guaranted to give always the same instance. It is needed if we keep global state in it. #Reusable do not give any guarantee.
If any class requests the instance of #Singleton annotated class, double checking is performed (which is slow). In case of #Reusable, it isn't.
I'd use #Reusable scope for classes that are expensive to build (for example I'm using for Retrofit instance - but to be honest I've never made performance tests if it is worth to use this annotation at all).
On the other hand, I'm using #Singleton annotated class for the cache.
Also, if you have class which keeps encapsulated global state like this:
class StateWrapper {
final State state;
#Inject
StateWrapper(State state) {
this.state = state;
}
}
I mean the state is de facto kept in the State class, do not annotate StateWrapper as #Singleton, always annotate the smallest part: in this case the State class.
(This hint is taken from the video)

pitfalls in builder inside singleton method controller?

Lets say I have controller RequestController in Spring which is marked as Singleton. Inside this controller there is a builder which is injected using dependency injection. The main goal for this class is to receive requests and build responses.
#Singleton
class RequestController {
private ResponseBuilder responseBuilder;
private RequestController(ResponseBuilder responseBuilder){
this.responseBuilder=responseBuilder;
}
public Response getResponse(Request request) {
return responseBuilder.getRequest(request).build();
}
}
My question:
What kind of pitfalls does this code hide? What could go wrong when we try to use it in normal spring application. #Singleton is only an information that this class will be created only once per applications.
I know that builder should be thread-safe since it will be responsible for handling multiple requests. But is anything else dangerous here?
Before going into your question there's one thing to be mentioned. You have declared your class RequestController as Singleton with #Singleton. If your class is a singleton you should make sure it is immutable, so no state change after creation. So I assume it is a stateless class. So you don't need to have a private constructor, which looks rather messy. Instead you can use,
#Inject
private RequestController(ResponseBuilder responseBuilder){
this.responseBuilder=responseBuilder;
}
Please note that, if you maintain a a good design, ResponseBuilder class should be an inject-able one. And RequestController class should be called only by injection.
Back to your problem, I think you have almost no problem. We should be very careful about what our real problem is? rather than what patterns we could drag and drop into our code?
Making a Controller, a Singleton is pretty much fine. But I don't find any need to use Builder pattern to your ResponseBuilder (you can change the name also). If your classes are rather simple and have just limited number of operations (a sign of a good design), you would never need builder pattern for your lifetime. It's more like we try to tear the paper with an axe. Why don't you use bare hands?
We should only use Builder in situations where we have to make considerably large scope class for some reason. You can have a good example of the use of Builder pattern in Hamcrest. It's an assertion tool for Java testing developed by Google. They have used builder pattern for some classes just to make life easier for the programmer who uses that by providing multiple list of tasks out of a single object.
Thank for a reply...I have an idea what it can be wrong with this code...Of course I should use injection on ResponseBuilder. But classically builder pattern have a state so in stateless controller we're using statefull class provided by ResponseBuilder. So automatically builder if it's not thread safe it can cause concurrency problems (race condition). Whenever multiple threads try to get access to builder fields they can get different state (because builder is not thread safe). So when we try to make builder thread safe it will work but a new problem will arise. Since our builder become thread safe only one thread will be able to use it and this can lead us to bootleneck for requests (multiple requests/threads use our method but they will be blocked by builder which is thread safe). Gimme a shout if my thinking is good :)

Extending application or using singletion?

I have an android project where i have different objects that one or more of my activities need to acess now i was thinking of creating a subclass of Application however under the documentation of Application it states the following:
There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
My question is fairly simple is it best pratice to use a static singleton class to contain all of your objects ? or am i right to assume that extending application is a better option?
To answer your question I would use a singleton container to access these objects, initialize that class with a context by application context (there are very big chances you will need a Context); but then you will see it's kind of hard to maintain these and the singleton container.
To solve this object graph issue, I would use some IoC: RoboJuice, AndroidAnnotations or Dagger are really cool and they provide much more. Each of them handles this issue different, but you don't have to worry about that.
I hope it helps!

How do I write a Guice Provider that doesn't explicitly create objects?

Say I have a ClassWithManyDependencies. I want to write a Guice Provider for this class, in order to create a fresh instance of the class several times in my program (another class will depend on this Provider and use it at several points to create new instances).
One way to achieve this is by having the Provider depend on all the dependencies of ClassWithManyDependencies. This is quite ugly.
Is there a better way to achieve this?
Note - I certainly don't want the Provider to depend on the injector. Another option I considered is having ClassWithManyDependencies and ClassWithManyDependenciesProvider extend the same base class, but it's butt ugly.
As mentioned on the mailing list, anywhere you can inject ClassWithManyDependencies you can simply inject Provider<ClassWithManyDependencies> instead, no need to write anything special yourself. Guice does this for you.
You shouldn't have to write a provider except to integrate with other frameworks.
Just DON'T bind your ClassWithManyDependencies in scope SINGLETON and in the class that wants to build many instances, instead of having a ClassWithManyDependencies instance injected you have a Provider injected. (Guice can do that for free for every binded class)
On this provider you can just call get(), if not in scope SINGLETON it makes a fresh new instance each time.
Now if you are in the tricky case that ClassWithManyDependencies relies both on some GUICE IOC and on some constructor parameters, then you shall go for Assisted Injections

Is there ever a case for 'new' when using dependency injection?

Does dependency injection mean that you don't ever need the 'new' keyword? Or is it reasonable to directly create simple leaf classes such as collections?
In the example below I inject the comparator, query and dao, but the SortedSet is directly instantiated:
public Iterable<Employee> getRecentHires()
{
SortedSet<Employee> entries = new TreeSet<Employee>(comparator);
entries.addAll(employeeDao.findAll(query));
return entries;
}
Just because Dependency Injection is a useful pattern doesn't mean that we use it for everything. Even when using DI, there will often be a need for new. Don't delete new just yet.
One way I typically decide whether or not to use dependency injection is whether or not I need to mock or stub out the collaborating class when writing a unit test for the class under test. For instance, in your example you (correctly) are injecting the DAO because if you write a unit test for your class, you probably don't want any data to actually be written to the database. Or perhaps a collaborating class writes files to the filesystem or is dependent on an external resource. Or the behavior is unpredictable or difficult to account for in a unit test. In those cases it's best to inject those dependencies.
For collaborating classes like TreeSet, I normally would not inject those because there is usually no need to mock out simple classes like these.
One final note: when a field cannot be injected for whatever reason, but I still would like to mock it out in a test, I have found the Junit-addons PrivateAccessor class helpful to be able to switch the class's private field to a mock object created by EasyMock (or jMock or whatever other mocking framework you prefer).
There is nothing wrong with using new like how it's shown in your code snippet.
Consider the case of wanting to append String snippets. Why would you want to ask the injector for a StringBuilder ?
In another situation that I've faced, I needed to have a thread running in accordance to the lifecycle of my container. In that case, I had to do a new Thread() because my Injector was created after the callback method for container startup was called. And once the injector was ready, I hand injected some managed classes into my Thread subclass.
Yes, of course.
Dependency injection is meant for situations where there could be several possible instantiation targets of which the client may not be aware (or capable of making a choice) of compile time.
However, there are enough situations where you do know exactly what you want to instantiate, so there is no need for DI.
This is just like invoking functions in object-oriented langauges: just because you can use dynamic binding, doesn't mean that you can't use good old static dispatching (e.g., when you split your method into several private operations).
My thinking is that DI is awesome and great to wire layers and also pieces of your code that needs sto be flexible to potential change. Sure we can say everything can potentially need changing, but we all know in practice some stuff just wont be touched.
So when DI is overkill I use 'new' and just let it roll.
Ex: for me wiring a Model to the View to the Controller layer.. it's always done via DI. Any Algorithms my apps uses, DI and also any pluggable reflective code, DI. Database layer.. DI but pretty much any other object being used in my system is handled with a common 'new'.
hope this helps.
It is true that in today, framework-driven environment you instantiate objects less and less. For example, Servlets are instantiated by servlet container, beans in Spring instantiated with Spring etc.
Still, when using persistence layer, you will instantiate your persisted objects before they have been persisted. When using Hibernate, for example you will call new on your persisted object before calling save on your HibernateTemplate.

Categories

Resources