How to package Factories in Java - java

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.

Related

Static factories and dependency injection

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.

What is equivalent to a package-private interface for encapsulating internal functionality of a package?

I am attempting to encapsulate all of the internal functionality of a service package. Most of my classes and methods are package-private. I have some internal interfaces that I don't want to expose outside of the package. I can make the interface itself package-private however all of the methods are still public (the default scope for interface methods).
What are my options for eliminating the public method signatures from my internal implementations in this package?
I am using interfaces so that I can easily switch out implementations using spring.
Some Things to Consider: Development tools that use source code analysis will report the interface methods as public API methods. For example a UML generator would generate a misleading UML diagram that incorrectly shows this as a public method.
One possible solution, as already #Bart has pointed out, is to use abstract classes instead of interfaces. A possible problem connected with this concept is a single-inheritance issue.
Another solution could be a separation of the "private" interfaces in a different package which doesn't need to be published together with your service package thought this method can quite ruin semantics of the interfaces, specially if one logical interface would have "private" and "public" part.
Last work around which has come to mind is to utilize some patter e.g. Double dispatch or Visitor could be useful.

Best approach for dynamic class and package loading in Java

I have a factory class that creates objects of a certain type (say, MyClass).
The factory class belongs to a specific package and I want to dynamically switch between implementations in that package and a newer version, for testing purposes.
Say, for example, that the original package is pack1 and the newer version is pack2, with class names pack1.Factory and pack2.Factory. The selection of pack1 or pack2 would be specified via a simple parameter in a property file. Furthermore, the MyClass type is common for both packages and only plain vanilla Java (i.e., no third-party libraries) should be used.
I am thinking of using Class.forName() for loading either pack1.Factory or pack2.Factory (depending on the property specified) and then invoking all factory methods via reflection.
Is that the best approach?
This is almost a classical usecase for an injection of control. Guice should get you started in no time.
There is a need to have an interface such as IFactory, with some factory method create. Create two Guice modules -- in one bind IFactory to pack1.Factory and in another to pack2.Factory. Of course, both these factories should implement IFactory.
Then in the main method process your parameter that determines what factory should be used, and create an injector based on one of the modules respectively.
You should avoid reflection where ever possible. It makes your code harder to understand, harder to refactor and harder to maintain.
Instead you could let your factory class implement an interface, create an instance of the factory you want to test and call your test with this instance.

Automatically binding multiple interfaces to one impl in Guice

I have a design like the own shown below, with one interface extending multiple parent interfaces, and one implementation of that interface.
In my client classes I want to depend only on one or more of the parent interfaces, rather than the ZooKeeperClient. I feel like this is a better design as it reduces the surface area of my client class's dependencies, and it also makes it easier to mock things in tests.
e.g.
#Inject
public Foo(ServiceUpdater su) {
// ...
}
However, in order to achieve this I need to manually add bindings from each interface to the implementation class:
bind(ServiceCreator.class).to(ZooKeeperClientImpl.class)
bind(ServiceDeleter.class).to(ZooKeeperClientImpl.class)
bind(ServiceUpdater.class).to(ZooKeeperClientImpl.class)
// ...
bind(ZooKeeperClient.class).to(ZooKeeperClientImpl.class)
Is there any way I can avoid this repetition and tell Guice to bind the whole hierarchy at once? Something like...
bind(ZooKeeperClient.class/* and its parents*/).to(ZooKeeperClient.class)
If not, is there something wrong with my design here? Am I doing something un-Guicy?
There is no such way in Guice, you may use a utility like ClassUtils.getAllInterfaces() to iterate over all interfaces and bind them.
In Silk you can do autobind on the implementation type.
autobind(ZooKeeperClientImpl.class).toConstructor();
This will bind the class to all its interfaces and super classes (except Object). These binds are weaker than explicit binds - so binding one of ZooKeeperClientImpl super types to something else
bind(ServiceUpdater.class).to(AnotherImplementation.class);
would dominate the autobind done so that you don't get conflicts because of ambiguous binds.
Silk is very much like Guice so if you don't have to much Guice code it is easy and fast to change.

Hiding classes in a jar file

Is it really impossible to hide some classes in a jar file?
I wanted not to allow direct instantiation of the classes to keep it more flexible. Only the factory (or a facade) should be visible of this jar.
Is there any other way than solve this problem than creating two projects?
(Two projects: the first one contains the classes (implementation) and the other one references to the first one and contains the factory; later only the second one will be referenced)
I'm understanding you're not looking to hide the actual classes, just prevent their construction outside a factory class. This I think can be quite easily achieved by using package private (default) visibility in the class constructors. The only limitation is that you'll need to have the classes and the factory in the same package so in a medium to large codebase things may get unnecessarily complex.
If I understand your question correctly, you would like to make sure that users of your library are forced to use your factory to instantiate their objects rather than using the constructors themselves.
As I see it there are two possibilities, one of which is silly but usable in few, specific cases, and the other one is the most practical and probably most commonly used way of doing it.
You could make all your classes into
private inner classes of the
factory. This would work if you had
one factory per class, but is hardly
workable if you have a lot of
different classes being managed
through one factory.
You could use the protected access modifier to
restrict access to your class
constructors. This is common
practice when using the factory
pattern.
I think you will have either compiler failure or warning if your public factory method try to return something which is "hidden".
No, you can not hide a public class without reimplementing your own ClassLoader or using OSGi or anything similar.
What you can do is to separate interface api from the implementation, e.g. have one project which contains only the interfaces and another porject which contains the implmentations. However, you still cannot hide the implementation classes.
Obfuscation can help you somehow.
With standard classloaders and plain old jar files, this is not possible. OSGi has this concept of making visible only some packages to another bundle(i.e. separation of public api and internal implementation).
If you are using eclipse, you may enforce such rules with this
If I understand you correctly when you say "not to allow direct instantiation of the classes to keep it more flexible", a properly executed facade pattern will handle this.
Restrict the constructors of all the classes you want to hide to package scope. Open the facade class to public scope.
http://mindprod.com/jgloss/packagescope.html
"If you have a variable or method in
your class that you don’t want clients
of your class directly accessing,
don’t give it a public, protected or
private declaration. Due to an
oversight in the design of Java, you
can’t explicitly declare the default
“package” accessibility. Other members
of the package will be able to see it,
but classes outside the package that
inherit from yours, won’t. The
protected accessibility attribute
offers slightly more visibibily. A
protected method is visible to
inheriting classes, even not part of
the same package. A package scope
(default) method is not. That is the
only difference between protected and
package scope. "
There are two solutions to your question that don't involve keeping all classes in the same package.
The first is to use the Friend Accessor/Friend Package pattern described in (Practical API Design, Tulach 2008).
The second is to use OSGi. There is an article here explaining how OSGi accomplishes this.
Related Questions: 1, 2, 3, and 4.
You can do such magics with a custom class loader but:
the correct separation will be available only in a project staffed with your class loader;
it's really doubtful that the effort to create such loader is worthy.
In such situations I would do something similar to what we may see in the standard Java. E.g.you see javax.xml.stream.XMLInputFactory but somewhere you have com.sun.xml.internal.stream.XMLInputFactoryImpl. It is perfectly compilable if you write:
new com.sun.xml.internal.stream.XMLInputFactoryImpl()
though you will hardly do it :-) With a system property you may control the actual implementation that is being loaded. To me such approach is fine in many situations.
I hope I have understood your question correctly ;)
Cheers!

Categories