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!
Related
So I've been playing around with Dagger2 with Android for a little bit and I'm starting to wrap my head around how dependencies are injected. I understand that for building components, one of the more common places for this code is in your Application class. This way I can call getApplication().getMyComponent() from my various activities, and inject the relevant fields into the Activity.
However, let's say I have a POJO and I want to inject another POJO into this (say a Service object with a DAO object inside it) and I'm injecting it using POJOComponent. Now, I can't build this in the Application class like before because I'm no longer injecting into an Activity (i.e. no access to 'getApplication()'), so my question is this; should I just build the component in the Service object and then inject the DAO? This doesn't seem correct to me, since if I wanted to inject the DAO into a different object/class, I would need to build my component in that object as well.
Surely I should just have to build my component once and use to inject the DAO into different objects/classes? One way I could think of was using static methods in the Application class but this feels like a hack. Any guidance would be appreciated!
Never use static methods or variable, if you can avoid it. There is most likely a better way.
If you have a android.app.Service, that service itself is/has a Context and you can just as easily get the Application and/or create a new component with that service context.
Then you can just inject it as you would with activities, or fragments.
If you are talking about Service as some sort of business logic class, then you have access to the constructor. In this case you can—and should—make use of Constructor injection.
If you need MyDao, put it in the constructor. Don't get into the habit, that each class grabs and takes the dependencies it needs. If something wants to use your service, it needs to supply it with the dao.
Wherever you use your Service class, there you should think about how to provide those dependencies. This will most likely be in an Activity, Application, Fragment, or Service again, where—as already pointed out above—you'll have access to the application and component again.
I want to ask whether the ServiceLoader.load() can help me create multiple instances of the loaded service?
I have been doing some testing and its seems it can only load one instance of the service at a time. If it is possible to have multiple instances, can someone explain how I can achieve this?
You don't want to use the ServiceLoader itself to create multiple copies. You could, using the reload method of the loader, but that is not the intended usage of it, probably doesn't perform very well, and also has the side effect that other implementations are reloaded as well.
More likely, what you want to do is instead of create a factory class (or some similar concept), which itself creates the instances of the class you actually want to use, in the end, and use the service loader to load such factory instances instead.
two classes extend Application
One class I've registered in the Manifest and am using as an Application is meant to be
Second class is my utilities class. It does lots of I/O and has a few helper methods. For I/O you need context (getAssets etc), so I reluctantly extended Application.
Note:
Everything is working as it should.
My Question:
Are there any drawbacks of using multiple Application classes? Is this even advised?
A few thoughts:
Like what would happen if I had onCreate and other callback methods defined in both the classes?
How do I register them both in the manifest even?
etc
PS: I know I can just use a field to store context in the second class.
I think this is not advised at all, because there is could only be one instance on Application (thus only one class).
I am very suspicious about what is really working. You're talking about utility class, so maybe you're using static methods that are working well. But you should use your debugger, and I'm almost certain that you'll discover that one of your classes is never instantiated.
By the way, the official documentation states that :
" There is normally no need to subclass Application. In most situations, 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. "
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.
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.