Creating object factories to improve testability and hide new operator - java

I am using DI to pass around my dependencies. But in some scenarios we need to create objects dynamically and do need to provide parameters during initialization. Code sample -a tries to explain the scenario.
In order to initialize such type of objects and hide new operator, I created simple factories. Code sample -b.
Code sample -a
int are used for simplicity they will/can actually be some real objects
public class Sample {
private final int c;
public Sample(int c){
this.c = c;
}
public void doSomething(SomeCommand command, Request request, Context context){
DynamicDependency dynamicDependency = new DynamicDependency(command.getA(), command.getB(), c);
dynamicDependency.doSomeWork(request, context);
}
}
class DynamicDependency{
private final int a;
private final int b;
private final int c;
public DynamicDependency(int a, int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
public void doSomeWork(Request request, Context context){
/*
Do work
*/
}
}
class SomeCommand {
private int a;
private int b;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
Code sample -b
public interface IParameterizedObjectFactory<T> {
T getInstance(Object... arguments) throws ClassCastException;
}
public class DynamicDependency implements IParameterizedObjectFactory<DynamicDependency> {
#Override
public DynamicDependencyFactory getInstance(Object... arguments) throws ClassCastException {
Validate.notNull(arguments);
if(arguments.length > 0){
final int a = (Integer) arguments[0];
final int b = (Integer) arguments[1];
final int c = (Integer) arguments[2];
return new DynamicDependency(a, b,c);
}
return null;
}
}
This does the job as I can now inject factory and then use it to get the new object as:
DynamicDependency dynamicDependency = dynamicDependencyFactory.getInstance(a,b,c);
Question(s):
Though, it does the job but we need to pass around list of Object[s] and and we loose strong typing. Casting also will eat up some execution time. How can it be improved?
Another approach could be to not to use the interface at all and use concrete classes which have getInstance method with appropriate parameter list. Sounds reasonable to me.
public class DynamicDependencyFactory {
public DynamicDependency getInstance(int a, int b, int c) {
return new DynamicDependency(a, b,c);
}
}
What else can be done to hide new? Or should I use second approach to create concrete factories?
Note: I am trying to stay away from reflection

The second approach you suggested is much better than the first. You still have the option to extract an interface from that factory if required:
public interface IDynamicDependencyFactory {
DynamicDependency getInstance(int a, int b, int c);
}
Note the lack of generic type parameters. Your first suggestion of the following interface:
public interface IParameterizedObjectFactory<T> {
T getInstance(Object... arguments) throws ClassCastException;
}
seems completely unnecessary according to your example, and, as you have noted, the Object[] as the arguments makes it a very unpleasant and non-type safe API to work with.
If you really need to pass different argument types to the methods on the factory, then define an overload for each valid signature instead of just accepting an Object[]:
public interface IDynamicDependencyFactory {
DynamicDependency getInstance(int a, int b, int c);
DynamicDependency getInstance(double a, int b, BigDecimal c);
}
Better yet, if you can refactor your code so that it does not require such a factory then that could be beneficial (unless you do not have access to the Request and Context objects at the same time as the a, b, and c int values). For example, you can pull up the constructor arguments to be method parameters and treat your DynamicDependency more like a service (or singleton):
class DynamicDependencyService {
public void doSomeWork(Request request, Context context, int a, int b, int c){
//Do work
}
}
This way, an instance of DynamicDependencyService can be passed to your Sample object via the constructor.

I decided to go with a mixed approach, using factories where I do not have control on the runtime object being created and passing runtime data via methods where the control is with me.
Steven shared couple of good articles in the comments, posting here.
Factories are a code smell
runtime values should not be injected into a component's constructor
Fortunately I was already avoiding the constructor injection in case of runtime values. The problem was with the legacy code and the code which is not owned by our team. For now, for the code which is not owned by us we have to use constructor even though it will smell a bit :)

Related

Passing parameters by class fields, overridden class methods or Properties

I was wondering lately, which one of the three methods of passing parameters to the method - presented below - are the best for you, your CPU, memory and why. I am considering methods which allow me to pass more arguments in future, without changing the method signature.
If you know something better, I am here to listen and learn.
Pass by methods
Params.java
public interface Params {
int getParamOne();
int getParamTwo();
}
Calling
obj.foo(new Params() {
#Override
public int getParamOne() {
return 1;
}
#Override
public int getParamOne() {
return 2;
}
});
Receiving
public void foo(Params p) {
int p1 = p.getParamOne();
int p2 = p.getParamTwo();
}
Pass by class fields
Params.java
public class Params {
private int paramOne;
private int paramTwo;
// Getters and setters here
}
Calling and receiving
No magic here, just create a new Params object, use setters, pass it to the method and use getters.
Pass by Properties class
Calling
properties.put("paramOne", 1);
properties.put("paramTwo", 2);
obj.foo(properties);
Receiving
public void foo(Properties properties) {
int a = (int) properties.get("paramOne");
int b = (int) properties.get("paramTwo");
}
I was pleased to show an real-life example of code, which actually needs passing varying types and number of properties. I'm using the third method - passing by the properties:
public interface DataProvider {
public String getContent(Properties properties);
}
public class HttpProvider implements DataProvider {
#Override
public String getContent(Properties properties) {
InputStream in = new URL(properties.get("URL")).openStream();
String content = IOUtils.toString(in);
IOUtils.closeQuietly(in);
return content;
}
public class FtpProvider implements DataProvider {
#Override
public String getContent(Properties properties) {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(properties.get("server"), properties.get("port"));
ftpClient.login(properties.get("user"), properties.get("pass"));
// Get file stream and save the content to a variable here
return content;
}
}
One interface for a different methods of obtaining a file. I am not persisting that this is good or not, it's just an example of code I've stumbled upon in my current project in work and I was wondering if could it be done better.
The usage of a "Params" class is better than properties, in performance. The java compiler can handle such short lived classes quite well.
One sees properties on some constructors / factory methods, like for XML and such.
One sees a parameter containing class in larger systems, to keep the API restricted to one parameter, and not use overloaded methods.
I would do:
public class Params {
public final int a;
public final int b;
public Params(int a, int b) {
this.a = a;
this.b = b;
}
}
And in the class immediately use params.a.
For the rest there is also the Builder Pattern, but that would be more a substitute for a complex constructor.
Signatures in interfaces should not ever change!!! If you contemplate to change APIs in the future (i.e. change, add or remove a parameter), an acceptable way may be by incapsulating your parameters in objects in order to do not break signatures.

Other ways to add a parameter to initComponents [java-netbeans]

I have a huge problem with my GUI java project in netbeans.
It is well-known that the code compiled by netbeans is read-only and I need an other way to add a parameter to the initComponents method, besides calling a myInitComponents method, identical to initComponents, and calling it in the constructor.
Now I have this:
public class MainFrame {
public MainFrame() {
DefaultStyledDocument doc = new DefaultStyledDocument();
myInitComponents(doc);
}
myInitComponents (DefaultStyledDocument doc) {
//components
textModel = new javax.swing.JTextPane(doc);
//components
}
initComponents () {
//components
}
In this way it works, but every time I change something within the frame, I have to copy and pase all the new code of initComponents inside myInitComponent.
Moreover, this is a very awful way to do that.
Is there any other way to add that parameter?
Any help is appreciated!
You can add a parameter to the MainFrame constructor, place it in a field, use custom creation code in the properties table of the GUI builder.
There a couple of free code places to insert in the code of initComponents. Create custom code is such a place;
private final DefaultStyledDocument doc = new DefaultStyledDocument();
And in "custom creation code:"
new JTextPane(doc)
Which can also be used for custom panels etcetera.
I have a huge problem with my GUI java project in netbeans. It is well-known that the code compiled by netbeans is read-only and I need an other way to add a parameter to the initComponents method, besides calling a myInitComponents method, identical to initComponents, and calling it in the constructor
I think you are probably confused between using constructors for initializations and setters for accessing values.
This is as good as asking: if you have a class with attributes like a, b & c, how to create a setter which set all attributes. This is something you should avoid. You could just create an individual setter and getter for each property instead of trying to use an init to set all attributes.
You should be doing this:
class MyClass
{
private int a;
private int b;
private int c;
public MyClass(){
init();
}
private void init(){
a = 100;
b = 200;
c = 300;
}
public int getA(){return a;}
public int getB(){return b;}
public int getC(){return c;}
public void setA(int a){this.a = a;}
public void setB(int b){this.a = b;}
public void setC(int c){this.a = c;}
}
instead of this:
class MyClass
{
private int a;
private int b;
private int c;
public MyClass(){
init();
}
private void init(){
a = 100;
b = 200;
c = 300;
}
public void myInit(int a, int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
}
this is a very awful way to do that. Is there any other way to add that parameter?
So you asked, if you have one more attribute, say int d. How should I add it to the parameter list of myInit(). So you already start to see the problem with this approach for your class design.
If possible, we try to achieve low coupling and high cohesion in our design. When you dump various unrelated attributes within a single method, you are steering towards low cohesion (a method which is not performing a very specific task).
If you try to use a single method like myInit() and use it as a setter to set multiple fields, it can cause a number of problems.
What if the user only wants to set a specific attribute, and not the rest?
So to answer your question, use individual setters for each attribute, unless the attributes are closely related for example:
setLocation(int x, int y);
setBounds(int x, int y, int width, int height);
At last I fixed this in a very simple way. I inserted all the code needed for the DefaultStyleDocument in the initComponents() method by clicking on customize code and adding it as pre-creation code.
public class MainFrame {
public MainFrame() {
myInitComponents();
}
//delete the myInitComponents() method
initComponents () {
//code useful for the DefaultStyledDocument..
DefaultStyledDocument doc = new DefaultStyledDocument();
//components
textModel = new javax.swing.JTextPane(doc);
}
Hope this could be useful to somebody.

Storing References to Objects of Different Classes

I currently have two classes that I create objects from. I need an array that will store references (pointers) to these objects. Of what type should the array be?
ArrayList<Class1> visableObjs = new ArrayList<Class1>();
Will of course only store pointers to objects that stem from Class1. If I had an object from Class2 could I store it's pointer in the same array?
if you mean that the objects you store are instances of those two classes, you should make those classes inherit from a (custom?) class or interface and use that class/interface as the type to store in your array.
We can do like this. Its not good practice at all if objects are from different classes.
ArrayList<Object> visableObjs = new ArrayList<Object>();
or
ArrayList visableObjs = new ArrayList();
You could perhaps use generics to create a Choice class to hold a reference to one or other type, but not both:
public final class Choice<A,B> {
private final A a;
private final B b;
private final boolean isA;
private Choice(A a, B b, boolean isA) {
this.a = a; this.b = b; this.isA = isA;
}
public static <A,B> Choice<A,B> ofA(A a) {
return new Choice<>(a, null, true);
}
public static <A,B> Choice<A,B> ofB(B b) {
return new Choice<>(null, b, false);
}
public boolean isA() { return isA; }
public A getA() {
if(!isA) throw new IllegalStateException("Not a!");
return a;
}
public boolean isB() { return !isA; }
public B getB() {
if(isA) throw new IllegalStateException("Not b!");
return b;
}
// Purely for demo purposes...
public static void main(String[] args) {
Choice<Integer,String> ich = Choice.ofA(42);
Choice<Integer,String> sch = Choice.ofB("foo");
// This is why the isA is included; so we can tell a null A from a null B.
Choice<Integer,String> nil = Choice.ofA(null);
//
List<Choice<Boolean,String>> xs = new ArrayList<Choice<Boolean,String>>();
xs.add(Choice.ofA(true));
xs.add(Choice.ofB("neep"));
}
}
This should work for two unrelated classes. Or for two out of many related subclasses, where you want to restrict to only those two possibilities - and not any subclass of a more general class/interface.
Such a class should probably be extended to properly implement equals()/hashCode(), toString(), etc. (For some definition [documented] of 'properly'.)
Caveat: this may not compile first try - I don't have a javac handy to test it. But the idea should be clear.

Implementation of Friend concept in Java [duplicate]

This question already has answers here:
Is there a way to simulate the C++ 'friend' concept in Java?
(18 answers)
Closed 8 years ago.
How does one implement the friend concept in Java (like C++)?
Java does not have the friend keyword from C++. There is, however, a way to emulate that; a way that actually gives a lot more precise control. Suppose that you have classes A and B. B needs access to some private method or field in A.
public class A {
private int privateInt = 31415;
public class SomePrivateMethods {
public int getSomethingPrivate() { return privateInt; }
private SomePrivateMethods() { } // no public constructor
}
public void giveKeyTo(B other) {
other.receiveKey(new SomePrivateMethods());
}
}
public class B {
private A.SomePrivateMethods key;
public void receiveKey(A.SomePrivateMethods key) {
this.key = key;
}
public void usageExample() {
A anA = new A();
// int foo = anA.privateInt; // doesn't work, not accessible
anA.giveKeyTo(this);
int fii = key.getSomethingPrivate();
System.out.println(fii);
}
}
The usageExample() shows how this works. The instance of B doesn't have access to the private fields or methods of an instance of A. But by calling the giveKeyTo(), class B can get access. No other class can get access to that method, since it a requires a valid B as an argument. The constructor is private.
The class B can then use any of the methods that are handed to it in the key. This, while clumsier to set up than the C++ friend keyword, is much more fine-grained. The class A can chose exactly which methods to expose to exactly which classes.
Now, in the above case A is granting access to all instances of B and instances of subclasses of B. If the latter is not desired, then the giveKeyTo() method can internally check the exact type of other with getClass(), and throw an exception if it is not precisely B.
Suppose A.foo() should only be called by B. This can be arranged by a token that can only be generated by B.
public class B
{
public static class ToA { private ToA(){} }
private static final ToA b2a = new ToA();
void test()
{
new A().foo(b2a);
}
}
public class A
{
public void foo(B.ToA b2a)
{
if(b2a==null)
throw new Error("you ain't B");
// ...
}
}
Only B can generate a non-null B.ToA token. If both A and B do not leak this token to the 3rd party,
nobody else can invoke A.foo()
If A2 wants to friend B too, it needs a different token type. If it's the same token type, since A got a token of the type from B, A can pretend to be B to A2.
The check is done at runtime, not compile time, that is not perfect. Not a big deal though, since any 3rd party can only invoke A.foo() with a null, it can't be an innocent mistake which we want to check at compile time; it's probably malicious so we don't care to warn the caller at compile time.
In Java you can put both (or more) classes into the same package. All methods and fields with the protected qualifier can directly be accessed by all classes in that package.
I figured out another way to achieve the same. Basically you check the fully qualified name of the invoking class name. If it matches your "friend" function, then you give access, else you return null.
public class A {
private static int privateInt = 31415;
public static int getPrivateInt() {
if(Throwable().getStackTrace()[1].getClassName().equals(new String("example.java.testing.B")))
{
return privateInt;
}
else
{
return null;
}
}
}
package example.java.testing;
public class B {
public void usageExample() {
int foo = A.getPrivateInt; // works only for B
System.out.println(foo);
}
}

java return from private method to public

I have a public method and a private method. they are both supposed to return int values. The private method is the one that does all the work and the public is the one that is called from the main program. How can I return the results returned from the private method by the public method?
its like this
public int longer()
{
longer(a.length);
}
private int longer(int n)
{
int index
//find largest index recursively
//make recursive call longer(n-1)
return index;
}
I want to pass it up to the public method and then return it from there. Would I just return it from the public method by saying return longer.index; or something along those lines?
i guess i should clarify. n isnt index. idnex is being calculated based on whats being passed into the method. the public and the private is because its going to be a recursive method. i'll edit what i posted above to make itm ore accurate of what im trying to do. passing in an array and recursively working on it.
public int longer()
{
return longerInternal(a.length);
}
private int longerInternal(int n)
{
int index
//find largest index recursively
//make recursive call longer(n-1)
return index;
}
From your public method, you can call down into the private method. I renamed the private method so that there was not a naming collision for your methods. A simple implementation should look something like this:
public class MyClass {
private int[] a;
public MyClass(int[] _a) {
a = _a;
}
public int longer()
{
return longerInternal(a.length);
}
private int longerInternal(int n)
{
int index;
//do recursive call
return index;
}
}
And it can be called like this:
MyClass myClass = new MyClass(new int[]{1,2,3,4,5,10});
int result = myClass.longer();
First, you probably need better function names.
You'd call your public function getLonger(int n) and then pass it to your private longer(int n) function. When this function is done, it will return to getLonger(int n) and then back to the caller.
You mentioned in an answer to a comment that the "caller does not need to have access to all internal workings of a class."
To me that suggests that you want to use an interface.
Create an interface that describes the class that will contain that secret algorithm:
package com.stevej;
public interface Longer {
public int longer();
}
Implement that interface using your secret algorithm:
package com.stevej;
public class LongerImpl implements Longer {
private int longer(int n){
return 0; // whatever
}
#Override
public int longer() {
return longer(5); // whatever
}
}
Now the caller only creates objects using the interface definition, guaranteeing that there are no exposed methods that he can access by accident. That implementation is hooked to that interface-defined object:
package com.stevej;
public class LongerProcessor {
Longer longerImpl = new LongerImpl();
public LongerProcessor() {
super();
}
public int longer() {
return longerImpl.longer();
}
}
Now you can rewrite the implementation of Longer as often as you like. As long as the interface definition never changes, the caller (LongerProcessor) will never have a problem. Heck, you could have two or more different implementations (LongerImplRecursive, LongerImplBruteForce, and so on), each implementing Longer, and all in use in different places in the same program:
package com.stevej;
public class LongerProcessor {
Longer longerImpl;
public LongerProcessor(boolean useRecursive) {
super();
if (useRecursive){
longerImpl = new LongerImplRecursive();
}else{
longerImpl = new LongerImplBruteForce();
}
}
public int longer() {
return longerImpl.longer();
}
}
How cool is that? Since you tagged this question as "homework", I'm wondering if the problem is supposed to engage you to think about separating the contract (interface) from the implementation (implementing class).

Categories

Resources