Parameter vs field - java

I'm creating an abstract class with an abstract method example(boolean b, String s) that takes 2 parameters.
I want to create some methods for use inside that abstract method, but I need them to use those same parameters. So instead of constantly using foo(b,s), it would be nicer to just use foo().
I thought I could somehow store them in the class. However, my method is potentially spammed so it must not be slower.
public abstract class Example {
public abstract void example(boolean b, String s);
public void foo() {
// This method needs the parameters from the above method.
}
}
Possible solution:
public abstract class Example {
protected boolean b;
protected String s;
public abstract void example();
public void foo() {
// This method can now use 'b' and 's'
}
public void run(boolean b, String s) {
this.b = b;
this.s = s;
example();
}
}
If I use these parameters like in the last example above, will it make the process any slower?
Will it cause problems if a thread wants to use this method while another is not finished yet?

Before dealing with speed, let's deal with correctness:
Will it cause problems if a thread wants to use this method while another is not finished yet?
Assuming that both threads share the same object, the answer is "yes".
However, if you can make it so that each thread uses its own instance of your class, the answer would be "no", because re-assignments from other threads is possible only on shared objects.
If I use these parameters like in the last example above, will it make the process any slower?
Any speed difference between the two implementations would be minimal, falling into category of premature micro-optimizations. If saving parameters on the object makes sense from readability perspective, and if it does not create concurrency issues, do it; otherwise, keep using parameters.

If you have some methods which you want implementations of example() to use, and they need invocation-specific values of b and s, you can put those methods in an inner class:
class Example {
final class Inner {
final boolean b;
final String s;
Inner(boolean b, String s) {
this.b = b; this.s = s;
}
void foo() {
// This can use the values of b and s passed to run().
}
}
public abstract void example(Inner inner);
public void run(boolean b, String s) {
example(new Inner(b, s));
}
}
This is thread safe (with respect to b and s) because you're not storing the values in shared mutable fields.

Will it cause problems if a thread wants to use this method while
another is not finished yet?
Yes its a issue when more than two threads executing the same method and it will be race condition. Ideally you should not have any state in service class as you will run into issues in case of multiple threads
In terms of performance it wont have any impact
You should pass it as method parameters. If not possible due to some issue you can think of putting it in ThreadLocal

To answer your question:
If I use these parameters like in the last example above, will it make the process any slower?
Yes, anything executing within the code takes time. Setting the variables will take a nanosecond or two to execute; although this time increase it insignificant and not worth even considering.
Will it cause problems if a thread wants to use this method while another is not finished yet?
Depends.
Yes:
Do both threads share the object?
Do both modify the state of the object?
Do both threads concurrently access the object?
No:
Will the object be immutable.
Will the object be synchronized
If the object is used by both threads the way it is now, you will most likely occur problems.

I decided to create a class Execution that acts as an overlay to the parameters and also contains the methods that require those.
public class Execution {
public final boolean b;
public final String s;
Execution(boolean b, String s) {
this.b = b;
this.s = s;
}
public void foo(); // Uses 'b' and 's'
}
Abstract class:
public abstract class Example {
public abstract void example(Execution e);
public final void run(boolean b, String s) {
example(new Execution(b, s);
}
}
Implementation:
public class ExampleExample extends Example {
#Override
public void foo(Execution e) {
/*
* Do whatever you want because
* you have 'b', 's' and 'foo()'
* and whatever methods
* added to 'Execution'
*
*/
}
}
I don't know how it will affect the performance, doing it this way. But it solved the dilemma.
Thanks for all your suggestions!

Related

Why is this variable's type its own class? [duplicate]

What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?
By an "anonymous class", I take it you mean anonymous inner class.
An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.
I tend to use it as a shortcut for attaching an event listener:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener -- I can just instantiate an anonymous inner class without actually making a separate class.
I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.
Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:
public interface F<A, B> {
B f(A a);
}
You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:
public static int larger(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n > i)
return n;
return i;
}
And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:
public static int smaller(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n < i)
return n;
return i;
}
These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:
public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
for (T t : ts)
if (f.f(t))
return t;
return z;
}
You can use an anonymous class to use the firstMatch method:
F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
Boolean f(final Integer n) {
return n > 10;
}
};
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);
This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.
A nice library for programming Java in this style: Functional Java.
Anonymous inner class is used in following scenario:
1.) For Overriding(subclassing), when class definition is not usable except current case:
class A{
public void methodA() {
System.out.println("methodA");
}
}
class B{
A a = new A() {
public void methodA() {
System.out.println("anonymous methodA");
}
};
}
2.) For implementing an interface, when implementation of interface is required only for current case:
interface InterfaceA{
public void methodA();
}
class B{
InterfaceA a = new InterfaceA() {
public void methodA() {
System.out.println("anonymous methodA implementer");
}
};
}
3.) Argument Defined Anonymous inner class:
interface Foo {
void methodFoo();
}
class B{
void do(Foo f) { }
}
class A{
void methodA() {
B b = new B();
b.do(new Foo() {
public void methodFoo() {
System.out.println("methodFoo");
}
});
}
}
I use them sometimes as a syntax hack for Map instantiation:
Map map = new HashMap() {{
put("key", "value");
}};
vs
Map map = new HashMap();
map.put("key", "value");
It saves some redundancy when doing a lot of put statements. However, I have also run into problems doing this when the outer class needs to be serialized via remoting.
They're commonly used as a verbose form of callback.
I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)
Here's a swing example
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// do stuff here...
}
});
Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)
You use it in situations where you need to create a class for a specific purpose inside another function, e.g., as a listener, as a runnable (to spawn a thread), etc.
The idea is that you call them from inside the code of a function so you never refer to them elsewhere, so you don't need to name them. The compiler just enumerates them.
They are essentially syntactic sugar, and should generally be moved elsewhere as they grow bigger.
I'm not sure if it is one of the advantages of Java, though if you do use them (and we all frequently use them, unfortunately), then you could argue that they are one.
GuideLines for Anonymous Class.
Anonymous class is declared and initialized simultaneously.
Anonymous class must extend or implement to one and only one class or interface resp.
As anonymouse class has no name, it can be used only once.
eg:
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
Yes, anonymous inner classes is definitely one of the advantages of Java.
With an anonymous inner class you have access to final and member variables of the surrounding class, and that comes in handy in listeners etc.
But a major advantage is that the inner class code, which is (at least should be) tightly coupled to the surrounding class/method/block, has a specific context (the surrounding class, method, and block).
new Thread() {
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println("Exception message: " + e.getMessage());
System.out.println("Exception cause: " + e.getCause());
}
}
}.start();
This is also one of the example for anonymous inner type using thread
An inner class is associated with an instance of the outer class and there are two special kinds: Local class and Anonymous class. An anonymous class enables us to declare and instantiate a class at same time, hence makes the code concise. We use them when we need a local class only once as they don't have a name.
Consider the example from doc where we have a Person class:
public class Person {
public enum Sex {
MALE, FEMALE
}
String name;
LocalDate birthday;
Sex gender;
String emailAddress;
public int getAge() {
// ...
}
public void printPerson() {
// ...
}
}
and we have a method to print members that match search criteria as:
public static void printPersons(
List<Person> roster, CheckPerson tester) {
for (Person p : roster) {
if (tester.test(p)) {
p.printPerson();
}
}
}
where CheckPerson is an interface like:
interface CheckPerson {
boolean test(Person p);
}
Now we can make use of anonymous class which implements this interface to specify search criteria as:
printPersons(
roster,
new CheckPerson() {
public boolean test(Person p) {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
}
);
Here the interface is very simple and the syntax of anonymous class seems unwieldy and unclear.
Java 8 has introduced a term Functional Interface which is an interface with only one abstract method, hence we can say CheckPerson is a functional interface. We can make use of Lambda Expression which allows us to pass the function as method argument as:
printPersons(
roster,
(Person p) -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
);
We can use a standard functional interface Predicate in place of the interface CheckPerson, which will further reduce the amount of code required.
i use anonymous objects for calling new Threads..
new Thread(new Runnable() {
public void run() {
// you code
}
}).start();
Anonymous inner class can be beneficial while giving different implementations for different objects. But should be used very sparingly as it creates problem for program readability.
One of the major usage of anonymous classes in class-finalization which called finalizer guardian. In Java world using the finalize methods should be avoided until you really need them. You have to remember, when you override the finalize method for sub-classes, you should always invoke super.finalize() as well, because the finalize method of super class won't invoke automatically and you can have trouble with memory leaks.
so considering the fact mentioned above, you can just use the anonymous classes like:
public class HeavyClass{
private final Object finalizerGuardian = new Object() {
#Override
protected void finalize() throws Throwable{
//Finalize outer HeavyClass object
}
};
}
Using this technique you relieved yourself and your other developers to call super.finalize() on each sub-class of the HeavyClass which needs finalize method.
You can use anonymous class this way
TreeSet treeSetObj = new TreeSet(new Comparator()
{
public int compare(String i1,String i2)
{
return i2.compareTo(i1);
}
});
Seems nobody mentioned here but you can also use anonymous class to hold generic type argument (which normally lost due to type erasure):
public abstract class TypeHolder<T> {
private final Type type;
public TypeReference() {
// you may do do additional sanity checks here
final Type superClass = getClass().getGenericSuperclass();
this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}
public final Type getType() {
return this.type;
}
}
If you'll instantiate this class in anonymous way
TypeHolder<List<String>, Map<Ineger, Long>> holder =
new TypeHolder<List<String>, Map<Ineger, Long>>() {};
then such holder instance will contain non-erasured definition of passed type.
Usage
This is very handy for building validators/deserializators. Also you can instantiate generic type with reflection (so if you ever wanted to do new T() in parametrized type - you are welcome!).
Drawbacks/Limitations
You should pass generic parameter explicitly. Failing to do so will lead to type parameter loss
Each instantiation will cost you additional class to be generated by compiler which leads to classpath pollution/jar bloating
An Anonymous Inner Class is used to create an object that will never be referenced again. It has no name and is declared and created in the same statement.
This is used where you would normally use an object's variable. You replace the variable with the new keyword, a call to a constructor and the class definition inside { and }.
When writing a Threaded Program in Java, it would usually look like this
ThreadClass task = new ThreadClass();
Thread runner = new Thread(task);
runner.start();
The ThreadClass used here would be user defined. This class will implement the Runnable interface which is required for creating threads. In the ThreadClass the run() method (only method in Runnable) needs to be implemented as well.
It is clear that getting rid of ThreadClass would be more efficient and that's exactly why Anonymous Inner Classes exist.
Look at the following code
Thread runner = new Thread(new Runnable() {
public void run() {
//Thread does it's work here
}
});
runner.start();
This code replaces the reference made to task in the top most example. Rather than having a separate class, the Anonymous Inner Class inside the Thread() constructor returns an unnamed object that implements the Runnable interface and overrides the run() method. The method run() would include statements inside that do the work required by the thread.
Answering the question on whether Anonymous Inner Classes is one of the advantages of Java, I would have to say that I'm not quite sure as I am not familiar with many programming languages at the moment. But what I can say is it is definitely a quicker and easier method of coding.
References: Sams Teach Yourself Java in 21 Days Seventh Edition
The best way to optimize code. also, We can use for an overriding method of a class or interface.
import java.util.Scanner;
abstract class AnonymousInner {
abstract void sum();
}
class AnonymousInnerMain {
public static void main(String []k){
Scanner sn = new Scanner(System.in);
System.out.println("Enter two vlaues");
int a= Integer.parseInt(sn.nextLine());
int b= Integer.parseInt(sn.nextLine());
AnonymousInner ac = new AnonymousInner(){
void sum(){
int c= a+b;
System.out.println("Sum of two number is: "+c);
}
};
ac.sum();
}
}
One more advantage:
As you know that Java doesn't support multiple inheritance, so if you use "Thread" kinda class as anonymous class then the class still has one space left for any other class to extend.

What does the following code snippet do? [duplicate]

What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?
By an "anonymous class", I take it you mean anonymous inner class.
An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.
I tend to use it as a shortcut for attaching an event listener:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener -- I can just instantiate an anonymous inner class without actually making a separate class.
I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.
Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:
public interface F<A, B> {
B f(A a);
}
You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:
public static int larger(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n > i)
return n;
return i;
}
And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:
public static int smaller(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n < i)
return n;
return i;
}
These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:
public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
for (T t : ts)
if (f.f(t))
return t;
return z;
}
You can use an anonymous class to use the firstMatch method:
F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
Boolean f(final Integer n) {
return n > 10;
}
};
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);
This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.
A nice library for programming Java in this style: Functional Java.
Anonymous inner class is used in following scenario:
1.) For Overriding(subclassing), when class definition is not usable except current case:
class A{
public void methodA() {
System.out.println("methodA");
}
}
class B{
A a = new A() {
public void methodA() {
System.out.println("anonymous methodA");
}
};
}
2.) For implementing an interface, when implementation of interface is required only for current case:
interface InterfaceA{
public void methodA();
}
class B{
InterfaceA a = new InterfaceA() {
public void methodA() {
System.out.println("anonymous methodA implementer");
}
};
}
3.) Argument Defined Anonymous inner class:
interface Foo {
void methodFoo();
}
class B{
void do(Foo f) { }
}
class A{
void methodA() {
B b = new B();
b.do(new Foo() {
public void methodFoo() {
System.out.println("methodFoo");
}
});
}
}
I use them sometimes as a syntax hack for Map instantiation:
Map map = new HashMap() {{
put("key", "value");
}};
vs
Map map = new HashMap();
map.put("key", "value");
It saves some redundancy when doing a lot of put statements. However, I have also run into problems doing this when the outer class needs to be serialized via remoting.
They're commonly used as a verbose form of callback.
I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)
Here's a swing example
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// do stuff here...
}
});
Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)
You use it in situations where you need to create a class for a specific purpose inside another function, e.g., as a listener, as a runnable (to spawn a thread), etc.
The idea is that you call them from inside the code of a function so you never refer to them elsewhere, so you don't need to name them. The compiler just enumerates them.
They are essentially syntactic sugar, and should generally be moved elsewhere as they grow bigger.
I'm not sure if it is one of the advantages of Java, though if you do use them (and we all frequently use them, unfortunately), then you could argue that they are one.
GuideLines for Anonymous Class.
Anonymous class is declared and initialized simultaneously.
Anonymous class must extend or implement to one and only one class or interface resp.
As anonymouse class has no name, it can be used only once.
eg:
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
Yes, anonymous inner classes is definitely one of the advantages of Java.
With an anonymous inner class you have access to final and member variables of the surrounding class, and that comes in handy in listeners etc.
But a major advantage is that the inner class code, which is (at least should be) tightly coupled to the surrounding class/method/block, has a specific context (the surrounding class, method, and block).
new Thread() {
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println("Exception message: " + e.getMessage());
System.out.println("Exception cause: " + e.getCause());
}
}
}.start();
This is also one of the example for anonymous inner type using thread
An inner class is associated with an instance of the outer class and there are two special kinds: Local class and Anonymous class. An anonymous class enables us to declare and instantiate a class at same time, hence makes the code concise. We use them when we need a local class only once as they don't have a name.
Consider the example from doc where we have a Person class:
public class Person {
public enum Sex {
MALE, FEMALE
}
String name;
LocalDate birthday;
Sex gender;
String emailAddress;
public int getAge() {
// ...
}
public void printPerson() {
// ...
}
}
and we have a method to print members that match search criteria as:
public static void printPersons(
List<Person> roster, CheckPerson tester) {
for (Person p : roster) {
if (tester.test(p)) {
p.printPerson();
}
}
}
where CheckPerson is an interface like:
interface CheckPerson {
boolean test(Person p);
}
Now we can make use of anonymous class which implements this interface to specify search criteria as:
printPersons(
roster,
new CheckPerson() {
public boolean test(Person p) {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
}
);
Here the interface is very simple and the syntax of anonymous class seems unwieldy and unclear.
Java 8 has introduced a term Functional Interface which is an interface with only one abstract method, hence we can say CheckPerson is a functional interface. We can make use of Lambda Expression which allows us to pass the function as method argument as:
printPersons(
roster,
(Person p) -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
);
We can use a standard functional interface Predicate in place of the interface CheckPerson, which will further reduce the amount of code required.
i use anonymous objects for calling new Threads..
new Thread(new Runnable() {
public void run() {
// you code
}
}).start();
Anonymous inner class can be beneficial while giving different implementations for different objects. But should be used very sparingly as it creates problem for program readability.
One of the major usage of anonymous classes in class-finalization which called finalizer guardian. In Java world using the finalize methods should be avoided until you really need them. You have to remember, when you override the finalize method for sub-classes, you should always invoke super.finalize() as well, because the finalize method of super class won't invoke automatically and you can have trouble with memory leaks.
so considering the fact mentioned above, you can just use the anonymous classes like:
public class HeavyClass{
private final Object finalizerGuardian = new Object() {
#Override
protected void finalize() throws Throwable{
//Finalize outer HeavyClass object
}
};
}
Using this technique you relieved yourself and your other developers to call super.finalize() on each sub-class of the HeavyClass which needs finalize method.
You can use anonymous class this way
TreeSet treeSetObj = new TreeSet(new Comparator()
{
public int compare(String i1,String i2)
{
return i2.compareTo(i1);
}
});
Seems nobody mentioned here but you can also use anonymous class to hold generic type argument (which normally lost due to type erasure):
public abstract class TypeHolder<T> {
private final Type type;
public TypeReference() {
// you may do do additional sanity checks here
final Type superClass = getClass().getGenericSuperclass();
this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}
public final Type getType() {
return this.type;
}
}
If you'll instantiate this class in anonymous way
TypeHolder<List<String>, Map<Ineger, Long>> holder =
new TypeHolder<List<String>, Map<Ineger, Long>>() {};
then such holder instance will contain non-erasured definition of passed type.
Usage
This is very handy for building validators/deserializators. Also you can instantiate generic type with reflection (so if you ever wanted to do new T() in parametrized type - you are welcome!).
Drawbacks/Limitations
You should pass generic parameter explicitly. Failing to do so will lead to type parameter loss
Each instantiation will cost you additional class to be generated by compiler which leads to classpath pollution/jar bloating
An Anonymous Inner Class is used to create an object that will never be referenced again. It has no name and is declared and created in the same statement.
This is used where you would normally use an object's variable. You replace the variable with the new keyword, a call to a constructor and the class definition inside { and }.
When writing a Threaded Program in Java, it would usually look like this
ThreadClass task = new ThreadClass();
Thread runner = new Thread(task);
runner.start();
The ThreadClass used here would be user defined. This class will implement the Runnable interface which is required for creating threads. In the ThreadClass the run() method (only method in Runnable) needs to be implemented as well.
It is clear that getting rid of ThreadClass would be more efficient and that's exactly why Anonymous Inner Classes exist.
Look at the following code
Thread runner = new Thread(new Runnable() {
public void run() {
//Thread does it's work here
}
});
runner.start();
This code replaces the reference made to task in the top most example. Rather than having a separate class, the Anonymous Inner Class inside the Thread() constructor returns an unnamed object that implements the Runnable interface and overrides the run() method. The method run() would include statements inside that do the work required by the thread.
Answering the question on whether Anonymous Inner Classes is one of the advantages of Java, I would have to say that I'm not quite sure as I am not familiar with many programming languages at the moment. But what I can say is it is definitely a quicker and easier method of coding.
References: Sams Teach Yourself Java in 21 Days Seventh Edition
The best way to optimize code. also, We can use for an overriding method of a class or interface.
import java.util.Scanner;
abstract class AnonymousInner {
abstract void sum();
}
class AnonymousInnerMain {
public static void main(String []k){
Scanner sn = new Scanner(System.in);
System.out.println("Enter two vlaues");
int a= Integer.parseInt(sn.nextLine());
int b= Integer.parseInt(sn.nextLine());
AnonymousInner ac = new AnonymousInner(){
void sum(){
int c= a+b;
System.out.println("Sum of two number is: "+c);
}
};
ac.sum();
}
}
One more advantage:
As you know that Java doesn't support multiple inheritance, so if you use "Thread" kinda class as anonymous class then the class still has one space left for any other class to extend.

Guice assisted inject overuse alternatives, dependency injection vs non-DI constructors

The main reasons I like passing in runtime dependencys in constructors are:
It makes the dependency required
It provides a central place to set instance variables
Setting the dependency as an instance variable prevents you from
having to pass it around from method to method within the class or pass it in twice or more
to two or more public methods
This has led me to use a lot of Assisted Injects when using Guice. This creates extra code compared to not using DI so reading things like this:
How exactly is Assisted-inject suppose to be use to be useful?
It seems like most people don't pass the runtime(derived, not available at startup) dependencies in constructors using assisted inject, and instead pass them in individual methods. Thats fine for the simple class given in the above stackoverflow post where there is only one method that relies on the dependency:
public class SomeClass {
#Inject
SomeClass(...) {
...
}
public void doWork(int s) { /* use s */ ... }
}
But what if the class has many methods that use the dependency? Do you pass it from the public method to private methods and require it passed in on all public methods?
For example:
public class SomeClass {
#Inject
SomeClass(...) {
...
}
public void doWork(int s) {
/*some code */
someOtherMethod(s);
anotherMethod(s);
}
//any private method that needs it gets it passed in as a param
private void someOtherMethod(int s)...
private void anotherMethod(int s)...
//require it passed in all public methods that need it
public void anotherPublic(int s){
someOtherMethod(s);
}
}
As opposed to using constructors this adds a bit of extra code as seen here:
public class SomeClass {
private int s;
SomeClass(int s) {
this.s = s;
}
public void doWork() {
someOtherMethod();
anotherMethod();
}
private void someOtherMethod()...
private void anotherMethod()...
public void anotherPublic(){}
}
Or would you set the instance var from the service method like this?
public class SomeClass {
Integer s;
#Inject
SomeClass(...) {
...
}
public void doWork(Integer s) {
/***set instance var this time***/
this.s = s;
someOtherMethod();
anotherMethod();
}
private void someOtherMethod()...
private void anotherMethod()...
public void anotherPublicMethod(){
if(s==null){ //check if s was set already
throw new IllegalStateException();
}else{
/* do something else */
}
}
}
Or would you pass the dependency into the other public method as a param and set the instance var there as well? For Example:
public class SomeClass {
#Inject
SomeClass(...) {
...
}
public void doWork(Integer s) {
/***set instance var this time***/
this.s = s;
someOtherMethod();
anotherMethod();
}
private void someOtherMethod()...
private void anotherMethod()...
public void anotherPublicMethod(Integer s){
this.s = s;
/* do something else */
}
}
So I think passing the param from method to method or throwing illegal state exceptions to check for it isn't ideal compared to using normal constructors, but obviously there are advantages/disadvantages to any framework/pattern.
If I am just not separating my objects in the ideal way, please let me know some guidelines you use, ie "I only use one public method per service class, see this book or post about it:.." .
What do you guys do in the above situations?
You nailed down some great reasons to use assisted injection in your question: It ensures that the object instances only ever exist in a fully-initialized state, keeps your dependencies together, and frees the object's public interface from requiring a predictable parameter in every method.
I don't really have any alternatives to add, other than the ones you mentioned:
Adding a setter method for that dependency, probably requiring IllegalStateException checks or a good default value
Creating an initialize(int s) pseudoconstructor method with the same IllegalStateException checks
Taking in the parameter in individual methods
Replacing the FactoryModuleBuilder boilerplate with a custom factory, thereby creating more extra boilerplate you're trying to avoid
My favorites are the two you seem to be deciding between--assisted injection or taking the parameter in every method--mostly because they both keep the object in a predictable, usable state at all times. My decision between them rests on what kind of state the object should carry, whether that state is mutable, and how I want to control instances. For Car.licensePlateNumber, the license plate number may vary with the car instance; each car has one license plate number that (in this example) never varies, and the car isn't valid without it, so it should be a constructor argument. Conversely, Repository<T> may frequently take in the same T instance in all of its methods, but a Repository is still a Repository no matter which instance you pass in, and you may want the freedom to reuse that instance without creating a new one for each T (as you may have to do with assisted injection). Both designs are valid, and each one is optimal for a certain set of cases.
Remember that there shouldn't really be that much extra code required for assisted injection:
/** In module: install(new FactoryModuleBuilder().build(SomeClass.Factory.class)); */
public class SomeClass {
public interface Factory {
SomeClass create(int s);
}
private final int s;
#Inject
SomeClass(/* ..., */ #Assisted int s) {
this.s = s;
}
public void doWork() { /* ... */ }
}

How to avoid code duplication in overloaded constructors?

Say that I have one constructor that takes an input and another that uses a default value. Both constructors then proceed to process this data in exactly the same way. (Example below.) What are my options to avoid code duplication in this case?
(I've read the post how to reduce the code of constructor overloading, where the top answer suggests using the keyword "this". In my case, I guess I would need to use "this" to call the first constructor from the second one after the input has been stored. This however results in a compilation error: "call to this must be first statement in constructor".)
Example code:
public class A {
public A(String a) {
//process a
}
public A() {
String a = "defaultString";
//process a
}
}
EDIT: I'm taking a lot of fire for using an input dialog call in a class constructor (which I'm aware isn't exactly good practice). So I've changed the code example to direct the discussion away from this :).
One way is to have an init method:
public class A {
public A(String a) {
init(a);
}
public A() {
String a = "defaultString";
init(a);
}
private void init(String a) {
//process a
}
}
Say that I have one constructor that takes an input and another that asks for it via an input dialog.
Don't do that. It will make for horribly entangled and hard to maintain code in the long run. At least try to seperate UI concerns (input dialogs etc) from your object model (which you can feed a string in the constructor).
In my honest opinion you really don't want an overloaded constructor here.
You may want to try chaining your constructors:
public class A {
public A(String a) {
//process a
}
public A() {
this("defaultString");
}
}
If you want to use a dialog to get the string, I recommend you present the dialog before calling this constructor.
I think this is the preferred method:
public class A {
public A(String a) {
//process a
}
public A() {
this(JOptionPane.showInputDialog("a"));
}
}
I'm not sure it is ever a good idea to call something like a JOptionPane from a constructor. This is just an idea but you really should take the buildA from a static method and perform it where you actually are intending on asking the user for input and then just call a single constructor.
public class A {
public A(String a) {
this.a = a;
}
public static A buildA(String input){
if(input == null){
input = JOptionPane.showInputDialog("a");
}
return new A(input);
}
}
Another option for reducing code duplication between constructors is to use an initialization block. Initialization block code will run before the constructor.
See
http://geekexplains.blogspot.com/2009/06/initializer-blocks-their-alternatives.html for an example, or
http://blog.sanaulla.info/2008/06/30/initialization-blocks-in-java/ for discussion of both static initializer blocks and instance initializer blocks.
Using this method, you could put the common code into the initializer block, then leave the different logic in the specific constructor.
public class A {
{
//initializer block - common code here
}
public A(String a) {
//constructor - specific code here
}
public A() {
//constructor - specific code here
}
}
This may not be ideal in all situations, but it is another way to approach the problem that I didn't see mentioned yet.

For two methods who need to call each other: how do I prevent an infinite loop?

I have two classes (A and B) which depend on each other in following sense:
Each class has a method performing some action.
The action of each class depends on an action of the other class.
So, if the user calls action of class A, it should automatically call
action of class B.
Same for the other way. But an infinite loop should be prevented.
I have found some code, which deals with this issue, but it seems to be a
little dumb to me: Infinite loop is prevented by locking.
import java.util.concurrent.locks.*;
import static java.lang.System.*;
import org.junit.*;
public class TEST_DependentActions {
static class A {
private B b = null;
private final ReentrantLock actionOnBLock = new ReentrantLock();
public void setB(B b) {
this.b = b;
}
public void actionOnB() {
if (!actionOnBLock.isLocked()) {
actionOnBLock.lock();
b.actionOnA();
actionOnBLock.unlock();
}
}
}
static class B {
private A a = null;
private final ReentrantLock actionOnALock = new ReentrantLock();
public void setA(A a) {
this.a = a;
}
public void actionOnA() {
if (!actionOnALock.isLocked()) {
actionOnALock.lock();
a.actionOnB();
actionOnALock.unlock();
}
}
}
#Test
public void test1()
throws Exception {
out.println("acting on class A first:");
A a = new A(); B b = new B();
a.setB(b); b.setA(a);
a.actionOnB();
}
#Test
public void test2()
throws Exception {
out.println("acting on class B first:");
A a = new A(); B b = new B();
a.setB(b); b.setA(a);
b.actionOnA();
}
}
Output is as following:
acting on class A first:
A : calling class B's action.
B : calling class A's action.
acting on class B first:
B : calling class A's action.
A : calling class B's action.
Well, it works, but doesn't seem to be an optimal solution.
How would you do it?
Is there a pattern which deal with such issue?
EDIT:
I want to know it in general.
But let's say I have a Container which contains multiple Elements.
The Container provides the method remove(someElement) and the
Element also provides a method removeMe().
Both methods depend on each other, but can't be connected to one
method, because both methods additionally perform some internal stuff, which is only
accessible inside each class.
I would handle this by rethinking the logic. Circular dependencies are typically a sign that something is a little ... off. Without more insight into the exact problem I can't be more specific.
Can you make one of the methods private/internal.
This should ensure only the other one can be called by client code, and you always know which way the calls work.
Alternatively, using your container/element example, something like this:
public class Container
{
public void Remove(Element e)
{
e.RemoveImplementation();
RemoveImplementation();
}
// Not directly callable by client code, but callable
// from Element class in the same package
protected void RemoveImplementation()
{
// Mess with internals of this class here
}
}
public class Element
{
private Container container;
public void Remove()
{
RemoveImplementation();
container.RemoveImplementation();
}
// Not directly callable by client code, but callable
// from Container class in the same package
protected void RemoveImplementation()
{
// Mess with internals of this class here.
}
}
I'm not sure if there is a common name for this pattern.
My recommendation would be to think less about the code and more about the design. Can the shared operations be abstracted into a new class which both classes can communicate with? Has the functionality been incorrectly shared across 2 classes?
At Uni this year they introduce the concept of "code smells", which is a bunch of "gut reactions" that code needs re-factoring. Perhaps could help?
For an overview try:
Wikipedia Code Smells or this book.
Perhaps you could tell us more about what you are trying to represent in the code?
I hope this helps.
The solution presented looks perfectly acceptable for the given scenario. But it really depends on what the actions mean whether this behaviour is correct or not. If this is exactly the behaviour that you want, then I'm not sure you have a problem.
Addendum:
In which case I'd say, split out the 'extra stuff' into a separate method, so that remove on the container can call the 'extra stuff' on the element without the recursive call back. Similarly, the extra stuff on the container can be separated so that removeMe can call a method on the container that only does the non-recursive stuff.
i think this could be solved by a boolean value global to the class (make it an instance variable of course). it checks if([the boolean variable]) and if it is true; it runs the call to the other method, if it is false it doesn't. just inside the if statement set the check equal to false. then at the end of each method make it set to true.
thats just how i would do it though.
If an exception is raised your implementation will not get unlocked. Locks can be expensive, a slight more light weight approach is to use an AtomicBoolean
private final AtomicBoolean actionOnBLock = new AtomicBoolean();
public void actionOnB() {
if (!actionOnBLock.getAndSet(true))
try {
b.actionOnA();
} finally {
actionOnBLock.set(false);
}
}
As others have suggested, a better way would be to write the code so one down not have to call the other. Instead you could have a method which calls A and B so the two objects don't need to know about each other.
public class AB {
private final A a;
private final B b;
public AB(A a, B b) {
this.a = a;
this.b = b;
}
public void action() {
a.action(); // doesn't call b.
b.action(); // doesn't call a.
}
}
As others have said, I think in most situations you should try to avoid this and refactor your code so the problem does not occur. But then there a certainly situations where this might not be an option or totally unavoidable. The most general approach to this is to ensure that before method A calls method B (and vice versa), it has to ensure the object of A is in state where an additional call to A immediately returns and thus results in a no-op. This is really very abstract and can be quite hard to apply to a concrete class and implementation.
Taking your example of container and element classes (say, C and E), where the C has a method C.remove(E e) and E has a method E.remove(), you could implement it like this:
class C:
elements = [...] // List of elements
remove(e):
if not elements.contains(e):
return
elements.remove(e)
// Do necessary internal stuff here...
// and finally call remove on e
e.remove()
class E:
container = ... // The current container of E
remove():
if container is none:
return
c = container
container = none
// Do necessary internal stuff here...
// and finally call remove on c
c.remove(this)
function fooA() calling fooB() and fooB() again calling fooA() is a valid recursion.
Recursion does not always have to be same function calling itself.
So, how do we prevent a recursive function from infinitely looping ?
By having a terminating condition right ?
I guess thats the way to go. However, I agree with other's comments on rethinking the design and avoid such recursions.
Simon's solution below also relies on the terminating conditions like
if not elements.contains(e):
return
and
if container is none:
return

Categories