In Effective Java (book), static factories are recommended.
On the other hand, keeping dependencies explicit, for example by using DI, is recommended.
But when I want to use a static factory, this explicitness will be skipped, because object instances will be received by calling the static factory method. With static factory methods, I won't have to pass in the object containing the static factory.
How can these two things go together?
Really good question.
Static factories have indeed this drawback (among others): they are not explicit and consequently they cannot be used as switchable dependencies.
I don't think that you can make the two things work together as a static method is associated to the class while the dependency injection is associated to instances.
So it is a choice of design.
Personally, I use the factory method as I don't want to allow to set explicitly the dependency returned by the factory.
It is the case as you want to master the objects creation : consistency, caching, and so for... and you want to provide a clear API.
It is a very straight way to guarantee that.
Setting an object with dependency injection will not provide that.
Generally, I did it for classes that I don't want neither to provide alternative implementations nor to mock during unit tests.
It is the case of business/model classes which I want to master the creation and also for some "utility" classes.
But as soon as the need to explicitly set the dependency happens, I refactor the static factory in something that allows to set the dependency explicitly.
If the master of the objects creation is always necessary, I transform the static factory into an instance factory that I inject.
Otherwise I inject directly the object that was returned by the factory.
There are two sides of the problem:
The object that is being created.
The object that is doing the
creating.
Factories, constructors, and auto-resolving containers are means of changing the way an object can be created (problem 2). That is entirely separate from how an object allows itself to be created (problem 1).
As a general heuristic:
Objects that are being created should be as flexible as possible in terms of how they can be constructed, and should explicitly advertise all their dependencies in their constructors (even if the constructors are made private and a factory is used by creators).
Creators should be as decoupled from the objects they created as your application needs to maintain its flexibility. Highly stable dependencies can be depended on directly. Dependencies that may change or be replaced should not
Differences between static factories, instance factories, constructors, and auto-resolution by container are largely just syntax. The biggest differences are semantic expression (what it communicates to a developer about the structure of the program) and the ability to resolve different implementations at runtime.
To answer your core question, the two things can go together because they are solutions to separate halves of the problem. You can use them both together.
Related
I have class A which instantiate class B which in turn do same for class C and so on, forming a large tree. I now need to instantiate an object that should be available all across the tree and I don't want to individually inject this object manually in all classes. I don't want to use a static because there could be different instances of class A running concurrently in different thread and this shared object must be unique per thread. I don't have much experience with thread safe operations.
Use Spring to manage the instance. That way you can inject your instance into any class that needs it and, provided the creation of the parent class is spring managed, the injected bean will be populated.
In some more detail, what you can do is define a class.
public class MyBean {
// Add your class details.
}
And ensure that Spring is either scanning its package or you have defined the bean in your applicationContext.xml file like this. The next stage is to inject this bean where you need to, using the #Autowired annotation..
#Autowired
private MyBean myBean;
And on the creation of that class, myBean will be populated with the same instance of MyBean that was initially created.
Advantages
Doing it this way means that your solution scales well. You can inject it anywhere without constantly changing constructors (and when you're creating more and more sub classes and relationships between classes, this is a prime candidate for Shotgun Surgery.
It's always good to learn about technologies that are used in industry.
Managing a single instance of a class using other methods (like the Singleton pattern) is usually a bad idea.
Disadvantages
Spring does a lot more than just inject objects, and you're pulling down a lot of classes to do just this, which will increase the size of your solution, although not significantly.
Extra Reading
Have a look at a basic Spring tutorial to get you going.
Have a look at the different scopes that you can create beans with, in case some of them suit your needs better.
You either need a local reference in the context that you want to use the object or you need a static reference. Since you don't want to use static you need to get a local reference. You can do this by passing the object in in the constructor or by adding a setter method. Then higher up the tree where ever you construct the child node you pass in the needed object.
You can have kind of a "Parallel Singleton" so to say, i.e. instead of having only one instance it will keep as many instances as there are threads, in a hashmap with a thread-related object being the key.
It's common to have an object used application wide.
What are the different patterns / models / ways to share an object through an application?
Is defining a "main class", then setting a member variable and extending all other classes from this "main class" a good way? Is creating a static class probably the better and cleaner way? What's your prefered pattern?
It's common to have an object used application wide. What are the different patterns / models / ways to share an object through an application?
One common way is to use the singleton pattern. I would avoid that though.
Is defining a "main class", then setting a member variable and extending all other classes from this "main class" a good way
Absolutely not. Aside from anything else, if it's an instance variable then it wouldn't be "shared" with instances of your other classes anyway. It's also a complete abuse of inheritance which would certainly bite you hard in any application of significant size - your other classes wouldn't logically have an inheritance relationship with your "main" class, would they? As a general rule, inheritance should only be used when it's really appropriate - not to achieve a quick fix.
What's your prefered pattern?
Dependency injection. When your application starts up, create all the appropriate objects which need to know about each other, and tell them (usually in the constructor) about their dependencies. Several different objects can all depend on the same object if that's appropriate. You can use one of the many dependency injection frameworks available to achieve this easily.
Dependency injection generally works better than using singletons because:
The class itself doesn't know whether or not the dependency is actually shared; why should it care?
Global state makes unit testing harder
Each class makes its dependencies clearer when they're declared - it's then easier to navigate around the application and see how the classes relate to each other.
Singletons and global factories are more appropriate when they're for things like logging - but even then, it means it's relatively hard to test the logging aspects of a class. It's a lot simpler to create a dependency which does what you need it to, and pass that to the object under test, than it is to add ways of messing around with a singleton (which usually remains "fixed" after initialization).
If you use a framework like Spring which has dependency injection, you can get all the benefits of "global" objects for free without needing to explicitly define them. You just create a reference to them in your application context and you can inject them into any object you'd like without worrying about issues with synchronizing.
Singleton pattern, AFAIK the preferable way in software engineering.
I believe what you are looking for is the Singleton Pattern. With this pattern you are ensured that only one instance of a class can be created in memory.
Example:
public class mySingletonClass {
private static mySingletonClass singleObject;
// Note that the constructor is private to prevent more than one
//instance of the class
private SingletonObjectDemo() {
// Optional Code
}
public static mySingletonClass getSingletonObject() {
if (singleObject == null) {
singleObject = new mySingletonClass();
}
return singleObject;
}
}
That said, you should try to avoid using it; but there are some acceptable cases, one of which is here.
What is the difference between creating a new object and dependency injection? Please explain in detail.
Well, they're not exactly comparable. You will always have to create a new object by instantiating a class at some point. Dependency injection also requires creating new objects.
Dependency injection really comes into play when you want to control or verify the behavior of instances used by a class that you use or want to test. (For Test Driven Development, dependency injection is key for all but the smallest example).
Assume a class Holder which requires an object of class Handle. The traditional way to do that would be to let the Holder instance create and own it:
class Holder {
private Handle myHandle = new Handle();
public void handleIt() {
handle.handleIt();
}
}
The Holder instance creates myHandle and no one outside the class can get at it. In some cases, unit-testing being one of them, this is a problem because it is not possible to test the Holder class without creating the Handle instance which in turn might depend on many other classes and instances. This makes testing unwieldy and cumbersome.
By injecting the Handle instance, for example in the constructor, someone from the outside becomes responsible for the creation of the instance.
class Holder {
private Handle myHandle;
public Holder(Handle injectedHandle) {
myHandle = injectedHandle;
}
public void handleIt() {
handle.handleIt();
}
}
As you can see the code is almost the same, and the Handle is still private, but the Holder class now has a much loser coupling to its outside world which makes many things simpler. And when testing the Holder class a mock or stub object can be injected instead of a real instance making it possible to verify or control the interaction between the Holder, its caller and the handle.
The actual injection would take place at some other place, usually some "main" program. There are multiple frameworks that can help you do that without programming, but essentially this is the code in the "main" program:
...
private Handle myHandle = new Handle(); // Create the instance to inject
private Handler theHandler = new Handler(myHandle); // Inject the handle
...
In essence, the injection is nothing more than a fancy set method. And of course, you can implement the injection mechanism using that instead of in the constructor like the simple example above.
Of course, both create objects. The difference is in who is responsible for the creation. Is it the class that needs its dependencies or a container like Spring for example, which wires the component's dependencies? You configure the dependencies in a separate(typically XML) configuration file.
It is really a separation of concerns. The class says I need this, this, and this component to function properly. The class doesn't care how it gets its components. You plug them into the class with a separate configuration file.
To give you an example let's consider having a shopping class that needs a payment module. You don't want to hardcode which payment module will be used. To achieve this you inverse the control. You can change the used payment module with a few keystrokes in the configuration file of the container. The power is that you aren't touching any Java code.
Well,
creating a new object is as explicit as it can get - you create a new instance of the desired class.
Dependency injections is a mechanism that provides you with references where you need them.
Imagine a class that represents a connection pool to your database - you usually only have one instance of that class. Now you need to distribute that reference to all the classes that use it.
Here is where Dependency Injection comes in handy - by using a DI framework such as Spring you can define that the one instance of your pool will be injected into the classes that need it.
Your question itself is not easy to answer since the creation of an object and dependency injection can't be compared that easily...
Dependency injections adds a layer of configurability into your application. In the sense, when you hard code object construction, you need to re-build and re-deploy your app, but when you use dependency injection, you can re configure the XML and change the behavior without re-building and re-deploying. There are a large variety of use cases where this can save a lot of tie and effort.
When using an inversion-of-control container to perform dependency injection, the container creates the objects, and not the developer. This is done so that the container can "inject" these objects into other objects.
The answer to the following question may also give the answer you are looking for: Why is the new operator an anti-pattern? Well, the simple answer is that using the new operator may create a hidden, inaccessible dependency within the containing class. This makes testing the containing class more difficult because it involves testing the hidden dependency at the same time (barring MOCK frameworks of course). However, you can avoid this situation by not using the new operator and injecting the dependent object instead. This also has the following advantages:
For test purposes you can inject a different object.
The resulting containing class is more reusable because it can support different implementations of the dependent object.
I have never found good answers to these simple questions about helper/utility classes:
Why would I create a singleton (stateless) instead of using static methods?
Why would an object instance be needed if an object has no state?
Often, singletons are used to introduce some kind of global state to an application. (More often than really necessary, to be honest, but that's a topic for another time.)
However, there are a few corner cases where even a stateless singleton can be useful:
You expect to extend it with state in the foreseeable future.
You need an object instance for some particular technical reason. Example: Synchonization objects for the C# lock or the Java synchronized statement.
You need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a different implementation.Example: The Toolkit.getDefaultToolkit() method in Java will return a singleton whose exact type is system dependent.
You want reference equality for a sentinel value.Example: DBNull.Value in C#.
I could see a case for a stateless singleton being used instead of a static methods class, namely for Dependency Injection.
If you have a helper class of utility functions that you're using directly, it creates a hidden dependency; you have no control over who can use it, or where. Injecting that same helper class via a stateless singleton instance lets you control where and how it's being used, and replace it / mock it / etc. when you need to.
Making it a singleton instance simply ensures that you're not allocating any more objects of the type than necessary (since you only ever need one).
Actually i've found another answer not mentionned here: static methods are harder to test.
It seems most test frameworks work great for mocking instance methods but many of them no not handle in a decent way the mock of static methods.
In most programming languages classes elude a lot of the type system. While a class, with its static methods and variables is an object, it very often cannot implement an interface or extend other classes. For that reason, it cannot be used in a polymorphic manner, since it cannot be the subtype of another type. For example, if you have an interface IFooable, that is required by several method signatures of other classes, the class object StaticFoo cannot be used in place of IFooable, whereas FooSingleton.getInstance() can (assuming, FooSingleton implements IFooable).
Please note, that, as I commented on Heinzi's answer, a singleton is a pattern to control instantiation. It replaces new Class() with Class.getInstance(), which gives the author of Class more control over instances, which he can use to prevent the creation of unneccessary instances. The singleton is just a very special case of the factory pattern and should be treated as such. Common use makes it rather the special case of global registries, which often ends up bad, because global registries should not be used just willy-nilly.
If you plan to provide global helper functions, then static methods will work just fine. The class will not act as class, but rather just as a namespace. I suggest, you preserve high cohesion, or you might end up with weirdest coupling issues.
greetz
back2dos
There is a trade-off between using which one. Singletons may or may not have state and they refer to objects. If they are not keeping state and only used for global access, then static is better as these methods will be faster. But if you want to utilize objects and OOP concepts (Inheritance polymorphism), then singleton is better.
Consider an example: java.lang.Runtime is a singleton class in java. This class allows different implementations for each JVM. The implementation is single per JVM. If this class would have been static, we cannot pass different implementations based on JVM.
I found this link really helpful: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html?
Hope it helps!!
Singleton is not stateless, it holds the global state.
Some reasons which I can think of using Singleton are:
To avoid memory leaks
To provide the same state for all modules in an application e.g database connection
For me "Want Object State use Singleton, Want Function use static method"
It depends on what you want. Whenever you want the object state (e.g. Polymorphism like Null state instead of null, or default state), singleton is the appropriate choice for you whereas the static method use when you need function (Receive inputs then return an output).
I recommend for the singleton case, it should be always the same state after it is instantiated. It should neither be clonable, nor receive any value to set into (except static configuration from the file e.g. properties file in java).
P.S. The performance between these 2 are different in milliseconds, so focus on Architecture first.
According to GoF’s book Design Patterns, chapter ‘Singleton’, class operations have the following drawbacks compared to singletons (bold emphasis mine):
More flexible than class operations. Another way to package singleton’s functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can’t override them polymorphically.
I was wondering how to package the factories that I have in my application. Should the Factory be in the same package as the classes that use it, in the same package as the objects it creates or in its own package?
Thanks for your time and feedback
Usually factories are in the same package as the objects they create; after all their purpose is to create those objects. Usually they are not in a separate package (there is no reason for that). Also having the factory be in the same package as the objects they create allows you to exploit package visibility.
The whole point of a Factory is to have a configurable way to create implementation instances for interfaces. The convention to have the factory in the same package as the implementation classes it provides adds a completely unnecessary restriction you're unlikely to meet in the future. Also if the implementation returned is not the same across all contexts, it makes even less sense to have it in the same package.
For example, imagine a service lookup factory that is shared between the client and server part of an application, which returns a client side implementation (which resides in a client-only package) on the client, and a server side implementation (in a server-only package) when called from within the server's runtime.
Your factory may even be configurable (we do this by having a XML file which defines which implementation class to return for which interface), so the implementation classes can easily be switched, or different mappings can be used for different contexts.
For example, when unit testing we use a configuration which returns mockup implementations for the interfaces (do be able to do unit tests that are not integration tests), and it would make no sense at all to require those mockup implementations to be in the same package as the factory, as they're part of the testing code rather than the runtime code.
My recommendation:
Don't add any package restrictions on
the implmentation classes, as you
don't know which implementations are
used in the future, or in different
contexts.
The interfaces may be in the same
package, but this restriction is also
unnecessary and only makes the
configuration rigid.
Configurable factories (such as a service lookup) can be reused and
shared across projects when the
interface/implementation mapping
isn't hardcoded. This point alone
justifies having the factory
separated from both the interfaces
and the implementation classes.
The unit of reuse is the unit of release. This means there shouldn't be coupling across packages, as the package is generally the lowest granularity of release. When you organize a package, imagine yourself saying, "here's everything you need to use these classes."
I like to put the factory in the package it is creating objects for, naming is key here, if naming is clear and transparent it will help maintenance effort down the line.
For example an action factory could be structured as:
package org.program.actions
interface org.program.actions.Action
enum org.program.actions.ActionTypes
factory org.program.actions.ActionFactory (or .ActionManager)
action implementation classes org.program.actions.LogAction, etc.
Following patterns like this throughout projects help project members to find classes where they actually are located in projects they haven't been involved in before.
That wholly depends on the way you're intending to use said factories. Sometimes it makes sense to put a factory in its own package.
You might for example have an interface, foo.bar.ui.Interface. You want to have different implementations of that interface, one for AWT, one for Swing, one for the console, etc. Then it would be more appropriate to create a foo.bar.ui.swing.SwingInterfaceFactory that creates a foo.bar.ui.swing.SwingInterface. The factory for the foo.bar.ui.awt.AWTInterface would then reside in foo.bar.ui.awt.AWTInterfaceFactory.
Point is, there is no always-follow-this rule. Use whatever is appropriate for your problem.
why not. make it as close as possible if there is no other objections. actually why not
public interface Toy
{
static class Factory
{
public static final Toy make() { ... }
}
}
Toy toy = Toy.Factory.make();
HA!
but make() shouldn't statically depend on subclasses of Toy, that would be bad. it can do some dynamic magic, depends on your factory strategy.