I have code that looks like this:
for(int i=0; i < a; i++){
List<Integer> list = elementA.get(i);
SomeClass rg = new SomeClass(list, a, methodA(i));
int result = rg.generate();
var+=methodA2(i, result);
}
for(int i=0; i < b; i++){
List<Integer> list = elementB.get(i);
SomeClass rg = new SomeClass(list, b, methodB(i));
int result = rg.generate();
var+=methodB2(i, result);
}
How can I avoid this code repetition? I can create function which does that, but what to do with this different methods?
Go to Windows >> Preferences >> Java >> Code Style >> Clean-Up Click on New button. In the next window provide a Profile Name of your choice for eg. JBT and click “OK”. It will take you to a new window where you can configure your clean up options.
The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup. The following finally block for the writeList method cleans up and then closes the PrintWriter and FileWriter .
With Java < 8 you can create an interface (note that there already is an IntFunction
interface in Java 8):
interface IntFunction<A> { A apply (int i); }
m(elementA, a, new IntFunction<A> () { public A apply(int i) { methodA(i); } });
And your method would look like:
private void m(Collection<List<Integer>> element, int a, IntFunction<A> f) {
for(int i=0; i < a; i++){
List<Integer> list = element.get(i);
SomeClass rg = new SomeClass(list, a, f.apply(i));
int result = rg.generate();
}
}
(I have omitted the methodA2
for conciseness: you would need a second interface that has an apply(int, int)
)
That is quite verbose and the benefit is not obvious vs. repetition.
With Java 8 it becomes cleaner:
m(elementA, a, i -> methodA(i));
//or
m(elementA, a, this::methodA);
List<List<Integer>>
as argument that returns the desired data.method
, method2
(based from your code).For example:
public long yourFooMethod(List<List<Integer>> listOfData, int n, SomeInterface foo) {
int i = 0;
long var = 0;
for(List<Integer> list : listOfData) {
SomeClass rg = new SomeClass(list, n, foo.method(i));
int result = rg.generate();
var += foo.method2(i, result);
}
return var;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With