are IoC containers singletons or static? - java

I'd like to better understand how IoC containers work and code up something to use for myself. Is there a best practice when creating the class for the container? Is it a singleton? is it static? Is it not a singleton but just has a bunch of static properties to hold resolved objects?

The IoC containers I know of are neither static nor singletons and I can't see any good reasons to make them. Just make it a normal class and create instances of it. There are scenarios where you might want to use several instances to separate independent concerns.
As you want to keep your components agnostic of the container, i.e. don't make them reference the container. If your component (the object which is being resolved by the container) needs to be able to access the container to get new instances, you would usually abstract an interface for this (commonly referred to as Service Locator Pattern (.NET, but it's all the same)), and let the container inject itself into the component. Again, no reason for static classes or methods.
One very good reason to follow this practice is that you are able to exchange the container implementation, for example switch to a 'professional' IoC framework, without touching your components at all.
Apart from that, there are a number of restrictions for static classes and methods in general, which you usually don't want, especially not when your system is likely to be changed, to grow and to get complex. To mention two: Static classes can't implement interfaces. Consequently you can never mock your container for testing purposes; Every usage of the container requires a fixed reference to the container assembly rather than to a contract. You cant subclass a static class;

Related

How to maintain a centralized Object across the application

I am developing an application where I need to create an object and multiple classes have to access and modify that object. How to see the recent changes made by the other class object and how to access the object centrally through all the classes with out passing that object as a parameter across all the classes?
I am creating an Apache POI document where I am adding multiple tables, multiple headers/footers and paragraphs. I want only a single XWPFDocument object present in my application.
Is there any design pattern we can achieve this?
Well the singleton design pattern would work - but isn't terribly clean; you end up with global static state which is hard to keep track of and hard to test. It's often considered an anti-pattern these days. There are a very few cases where it still makes sense, but I try to avoid it.
A better approach would be to use dependency injection: make each class which needs one of these objects declare a constructor parameter of that type (or possibly have a settable property). Each class shouldn't care too much about how shared or otherwise the object is (beyond being aware that it can be shared). Then it's up to the code which initializes the application to decide which objects should be shared.
There are various dependency injection frameworks available for Java, including Guice and Spring. The idea of these frameworks is to automatically wire up all the dependencies in your application, given appropriate configuration.
There is Singleton Pattern for this, it creates a single instance for the application and is shared without passing around.
But it not not the best of options.
Why is it a bad option?
It is not good for testability of code
Not extensible in design
Better than Singleton Pattern is an application wide single instance
Create a single object for the application and share it using some context object. More on this is explained by Misko in his guide to testable code
single instance and not Singleton Pattern
It stands for an application wide single instance, which DOES NOT inforce its singletonness through a static instance field.
Why are Singletons hard to test?
Static access prevents collaborating with a subclass or wrapped version of another class. By hard-coding the dependency, we lose the power and flexibility of polymorphism.
-Every test using global state needs it to start in an expected state, or the test will fail. But another object might have mutated that global state in a previous test.
Global state often prevents tests from being able to run in parallel, which forces test suites to run slower.
If you add a new test (which doesn’t clean up global state) and it runs in the middle of the suite, another test may fail that runs after it.
Singletons enforcing their own “Singletonness” end up cheating.
You’ll often see mutator methods such as reset() or setForTest(…) on so-called singletons, because you’ll need to change the instance during tests. If you forget to reset the Singleton after a test, a later use will use the stale underlying instance and may fail in a way that’s difficult to debug.

Composition vs multiple singletons

I'm writing a desktop MMO game and I want to consult on the architecture question. I have such classes as NetworkManager, ClientWindow, CachingTextureAtlas they are needed only in one instance for the game and here is my question: is it correct to make them singletons? If yes it will be a kind of interaction through the global classes which is not good from the design point of view as it seems to me and if no we'll compose them in a facade and we'll have to pass those all to constructors of too many classes which is not convinient as well. What is a better choice?
Singleton should be used carefully (almost never). I have seen many places, the recent sceanrio being hibernate session factory, where initially we thought that the single instance should be fine but then came across scenario for multiple instance and ended up refactoring the code.
Other problem is if you are writing unit tests for your code, then it will be a nightmare for all the classes which depends on these singleton classes.
One of the solution might be to inject a kind of factory which can provide you these instances/ it gives you a kind of indirection and avoid direct coupling. The other approach is to have a container (e.g. pico container) and inject as constructor dependencies which is what you have pointed out as well.

How to ensure a class can only be instantiated by Spring?

I am re-factoring a legacy Java application to use Spring.
This involves declaring the application classes as Spring beans and then replacing all occurrences of new with context.getBean OR with DI.
I'm re-writing application logic in way that some classes become singletons. However since they are being instantiated using new in other locations, multiple copies would exist which would mess up the business logic.
I'd like to ensure that application explicitly fails whenever it tries to instantiate an object by itself, instead of running and misbehaving in unpredictable ways. (I'm not sure that the re-factoring has covered 100% of the application there still might be new lurked up in some corner)
What is the best way of ensuring that a class can only be instantiated by Spring container?
(I'm hoping to avoid writing a factory for each class)
As from your question
In this particular scenario only one copy of an object should exist which is fetched from the context, multiple copies would mess up the business logic.
you can create classic singleton and use getInstance() method as factory method in bean definition in spring's xml file:
<bean id="myBean" class="MyClass" factory-method="getInstance"/>
Make your constructor private, and than no one can call it. Additionally you will see errors in compile time, if some parts of old code uses new to instantiate your class.

Why does StockWatcher.java use class variables instead of local variables in onModuleLoad?

So, yeah. That. I'm going through the tutorial one step at a time, so if the answer comes up later, forgive me. It's step 1 in this section.
I understand the ease of using this to have access in other methods in the EntryPoint class, but coming from the Spring MVC world, this sort of thing might be thought of as a controller and be a singleton (bean). Is it wrong to think this way in the GWT world?
With GWT you are coding as if it was a desktop AWT program. So, you do not have CDI or anything similar.
So, if you put all your information in a bean, you still would have to either:
keep a bean attribute in the class
pass it as a parameter in the method call
to get a reference to it (instead of retrieving it from CDI when needed)
While you can still use a bean when needed, these attributes are closely linked to the main class (in fact they are other graphical components to show). In general, I would only use bean when you have a bunch of attributes that are tightly coupled between them but are not tightly coupled to any other class.

when is a singleton class preferred over a class that has only static methods?

When is a singleton class preferred over a class that has only static methods and a private default constructor?
Please vote.
Use a singleton to better control when initialization occurs. With a static class, any initialization must be at class load-time, which you have little control over. For example, a simple reference to a static final MEMBER will trigger class loading. With a singleton, initialization can trivially be deferred till much later - typically, till first time of use.
Reasons to delay initialization may be:
it's expensive and you don't always need it for that class
you can't initialize till some other resource is initialized (say, a database connection). In this case, a lazily-instantiated singleton often provides correct order of operations without any explicit control - if it's not referenced till after the other resource is initialized, everything happens for free.
Use a singleton to improve testability. If you need to make some kind of mock object (in the broad sense) of the singleton in order to test its clients, one way to do it is to put an interface on its use, and supply a test singleton that's of a different class but implements the same interface.
Using a singleton makes initialization testing easier as well.
Use a singleton when you might need to debug initialization. Stack traces from static initialization can be puzzling. Debugging can be puzzling too. If the class is loaded early, it may break before a breakpoint on the first line in main() is even hit.
When is a singleton class preferred over a class that has only static methods and a private default constructor?
When you need an instance. For example, to pass as method argument.
The main reason for only having static methods is when you just need a toolbox to pack some functions together.
I use singletons for mainly two reasons:
It is really expensive (time or memory) to construct the object, and
I want to only ever do it once.
The data associated with the class
needs to be the same in every instance of the class.
If you have some state you need to store, a singleton is the way to go. For instance, if your class needs to load some configuration from a properties file.
Static method is not dynamic, this is a big different with singleton class instance. So if you need to extends from a class and override some method, the second way won't work.
And the for the second way, you may need to use some static references which may lead to memory leak.
I would say that a singleton class would be preferred only in one case: when you have some configuration to store that is system wide, will rarely (if ever) need to be refreshed.
As an example of what I mean, I have a singleton pattern in one of my applications that represents the NAT device of the user's internet connection. This application is intended for desktop use, and so would rarely (if ever) see a change in the internet connection. Presumably the user could carry their laptop to a new location, and this would change; however, there is a method to recreate the state in this event, but this is very infrequently changed state that can take several seconds to initialize.
This need to keep expensive, infrequently changing, and globally applicable state is best done by either an application scoped bean (my preferred option) or a singleton pattern bean. Static methods aren't as good for preserving this kind of state, though you could also accomplish this using static fields as well to make a pseudo-singleton. (Not sure if there's a better name for this - probably)
In general, my recommendation is not to use singleton like patterns if you can avoid it, as it makes re-use more difficult. If you're using a CDI framework, scope your bean at the application level for easier re-use. (This may not be a concern of yours - if not, you may safely ignore this advice)

Categories